Wordalist Enhancements

Userscript with enhancements for Wordalist

// ==UserScript==
// @name               Wordalist Enhancements
// @name:sv-SE         Wordalist Enhancements
// @namespace          martenb-se
// @version            0.2.0
// @author             martenb-se
// @description        Userscript with enhancements for Wordalist
// @description:sv-SE  Användarskript (userscript) med förbättringar för Wordalist
// @license            MIT
// @icon               https://wordalist.com/favicon.ico
// @match              https://wordalist.com/*
// @grant              GM_deleteValue
// @grant              GM_getValue
// @grant              GM_setValue
// @run-at             document-end
// ==/UserScript==

(l=>{const n=document.createElement("style");n.dataset.source="vite-plugin-monkey",n.textContent=l,document.head.append(n)})(` :root, .light, .light-theme {
  --black-a1: hsla(0, 0%, 0%, 0.012);
  --black-a2: hsla(0, 0%, 0%, 0.027);
  --black-a3: hsla(0, 0%, 0%, 0.047);
  --black-a4: hsla(0, 0%, 0%, 0.071);
  --black-a5: hsla(0, 0%, 0%, 0.090);
  --black-a6: hsla(0, 0%, 0%, 0.114);
  --black-a7: hsla(0, 0%, 0%, 0.141);
  --black-a8: hsla(0, 0%, 0%, 0.220);
  --black-a9: hsla(0, 0%, 0%, 0.439);
  --black-a10: hsla(0, 0%, 0%, 0.478);
  --black-a11: hsla(0, 0%, 0%, 0.565);
  --black-a12: hsla(0, 0%, 0%, 0.910);
}
:root, .light, .light-theme {
  --violet-1: hsl(255, 65.0%, 99.4%);
  --violet-2: hsl(252, 100%, 99.0%);
  --violet-3: hsl(252, 96.9%, 97.4%);
  --violet-4: hsl(252, 91.5%, 95.5%);
  --violet-5: hsl(252, 85.1%, 93.0%);
  --violet-6: hsl(252, 77.8%, 89.4%);
  --violet-7: hsl(252, 71.0%, 83.7%);
  --violet-8: hsl(252, 68.6%, 76.3%);
  --violet-9: hsl(252, 56.0%, 57.5%);
  --violet-10: hsl(251, 48.1%, 53.5%);
  --violet-11: hsl(250, 43.0%, 48.0%);
  --violet-12: hsl(254, 60.0%, 18.5%);
}
.CheckboxRoot {
  background-color: white;
  width: 25px;
  height: 25px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 10px var(--black-a7);
}
.CheckboxRoot:hover {
  background-color: var(--violet-3);
}
.CheckboxRoot:focus {
  box-shadow: 0 0 0 2px black;
}
.CheckboxIndicator {
  color: var(--violet-11);
}
.CheckboxForm .Label {
  color: white;
  padding-left: 15px;
  font-size: 15px;
  line-height: 1.6;
  margin-right: 10px;
}
.CheckboxForm > div {
  float: right;
}
:root, .light, .light-theme {
  --black-a1: hsla(0, 0%, 0%, 0.012);
  --black-a2: hsla(0, 0%, 0%, 0.027);
  --black-a3: hsla(0, 0%, 0%, 0.047);
  --black-a4: hsla(0, 0%, 0%, 0.071);
  --black-a5: hsla(0, 0%, 0%, 0.090);
  --black-a6: hsla(0, 0%, 0%, 0.114);
  --black-a7: hsla(0, 0%, 0%, 0.141);
  --black-a8: hsla(0, 0%, 0%, 0.220);
  --black-a9: hsla(0, 0%, 0%, 0.439);
  --black-a10: hsla(0, 0%, 0%, 0.478);
  --black-a11: hsla(0, 0%, 0%, 0.565);
  --black-a12: hsla(0, 0%, 0%, 0.910);
}
:root, .light, .light-theme {
  --mauve-1: hsl(300, 20.0%, 99.0%);
  --mauve-2: hsl(300, 7.7%, 97.5%);
  --mauve-3: hsl(294, 5.5%, 95.3%);
  --mauve-4: hsl(289, 4.7%, 93.3%);
  --mauve-5: hsl(283, 4.4%, 91.3%);
  --mauve-6: hsl(278, 4.1%, 89.1%);
  --mauve-7: hsl(271, 3.9%, 86.3%);
  --mauve-8: hsl(255, 3.7%, 78.8%);
  --mauve-9: hsl(252, 4.0%, 57.3%);
  --mauve-10: hsl(253, 3.5%, 53.5%);
  --mauve-11: hsl(252, 4.0%, 44.8%);
  --mauve-12: hsl(260, 25.0%, 11.0%);
}
:root, .light, .light-theme {
  --violet-1: hsl(255, 65.0%, 99.4%);
  --violet-2: hsl(252, 100%, 99.0%);
  --violet-3: hsl(252, 96.9%, 97.4%);
  --violet-4: hsl(252, 91.5%, 95.5%);
  --violet-5: hsl(252, 85.1%, 93.0%);
  --violet-6: hsl(252, 77.8%, 89.4%);
  --violet-7: hsl(252, 71.0%, 83.7%);
  --violet-8: hsl(252, 68.6%, 76.3%);
  --violet-9: hsl(252, 56.0%, 57.5%);
  --violet-10: hsl(251, 48.1%, 53.5%);
  --violet-11: hsl(250, 43.0%, 48.0%);
  --violet-12: hsl(254, 60.0%, 18.5%);
}
:root, .light, .light-theme {
  --purple-1: hsl(280, 65.0%, 99.4%);
  --purple-2: hsl(276, 100%, 99.0%);
  --purple-3: hsl(276, 83.1%, 97.0%);
  --purple-4: hsl(275, 76.4%, 94.7%);
  --purple-5: hsl(275, 70.8%, 91.8%);
  --purple-6: hsl(274, 65.4%, 87.8%);
  --purple-7: hsl(273, 61.0%, 81.7%);
  --purple-8: hsl(272, 60.0%, 73.5%);
  --purple-9: hsl(272, 51.0%, 54.0%);
  --purple-10: hsl(272, 46.8%, 50.3%);
  --purple-11: hsl(272, 50.0%, 45.8%);
  --purple-12: hsl(272, 66.0%, 16.0%);
}
:root, .light, .light-theme {
  --plum-1: hsl(292, 90.0%, 99.4%);
  --plum-2: hsl(300, 100%, 98.6%);
  --plum-3: hsl(299, 71.2%, 96.4%);
  --plum-4: hsl(299, 62.0%, 93.8%);
  --plum-5: hsl(298, 56.1%, 90.5%);
  --plum-6: hsl(296, 51.3%, 85.8%);
  --plum-7: hsl(295, 48.2%, 78.9%);
  --plum-8: hsl(292, 47.7%, 70.8%);
  --plum-9: hsl(292, 45.0%, 51.0%);
  --plum-10: hsl(292, 50.2%, 46.9%);
  --plum-11: hsl(292, 60.0%, 42.5%);
  --plum-12: hsl(291, 66.0%, 14.0%);
}
:root, .light, .light-theme {
  --gray-1: hsl(0, 0%, 99.0%);
  --gray-2: hsl(0, 0%, 97.3%);
  --gray-3: hsl(0, 0%, 95.1%);
  --gray-4: hsl(0, 0%, 93.0%);
  --gray-5: hsl(0, 0%, 90.9%);
  --gray-6: hsl(0, 0%, 88.7%);
  --gray-7: hsl(0, 0%, 85.8%);
  --gray-8: hsl(0, 0%, 78.0%);
  --gray-9: hsl(0, 0%, 56.1%);
  --gray-10: hsl(0, 0%, 52.3%);
  --gray-11: hsl(0, 0%, 43.5%);
  --gray-12: hsl(0, 0%, 9.0%);
}
.ToolbarRoot {
  padding: 10px;
  margin-top: 1.5em;
  margin-left: 1.5em;
  width: calc(100% - 1.5em);
  border-radius: 6px;
  background-color: var(--purple-6);
  box-shadow: 0 2px 10px var(--black-a7);
  /* Maximum minimizing capabilities */
  /* display: flex; */ /* Disabled for maximum resizing */
  /* min-width: max-content; */ /* Disabled for maximum resizing */
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.ToolbarToggleItem,
.ToolbarLink,
.ToolbarText,
.ToolbarButton {
  flex: 0 0 auto;
  color: var(--mauve-11);
  height: 25px;
  padding: 0 5px;
  border-radius: 4px;
  display: inline-flex;
  font-size: 13px;
  line-height: 1;
  align-items: center;
  justify-content: center;
}
.ToolbarToggleItem:hover,
.ToolbarLink:hover,
.ToolbarButton:hover {
  background-color: var(--violet-3);
  color: var(--violet-11);
}
.ToolbarToggleItem:focus,
.ToolbarLink:focus,
.ToolbarButton:focus {
  position: relative;
  box-shadow: 0 0 0 2px var(--violet-7);
}
.ToolbarLink,
.ToolbarText {
  background-color: transparent;
  justify-content: center;
  align-items: center;
  /* Maximum minimizing capabilities */
  /* display: inline-flex; */ /* Disabled for maximum resizing */
  display: inline; /* Allow resizing */
}
.ToolbarLink {
  color: var(--violet-11);
}
.ToolbarLink:hover {
  background-color: transparent;
  cursor: pointer;
}
.ToolbarButton {
  margin-right: 10px;
  padding-left: 10px;
  padding-right: 10px;
  color: white;
  background-color: var(--violet-9);
}
.ToolbarLink,
.ToolbarText,
.ToolbarButton {
  /* Line height fix when adding icon to buttons */
  vertical-align: middle;
}
.ToolbarLink svg,
.ToolbarText svg,
.ToolbarButton svg {
  margin-right: 5px;
  padding: 0;
  display: inline-block;
}
.ToolbarLink svg {
  /* Fix position due to parent having "display: inline" */
  position: relative;
  top: 0.2em;
}
.ToolbarButton.Warning {
  background-color: var(--plum-9);
}
.ToolbarButton:hover {
  background-color: var(--violet-10);
  color: white;
  cursor: pointer;
}
.ToolbarButton.Warning:hover {
  background-color: var(--plum-10);
}
/* Disabled button */
.ToolbarButton:disabled,
.ToolbarButton[disabled],
.ToolbarButton:disabled:hover,
.ToolbarButton[disabled]:hover{
  background-color: var(--gray-9);
  cursor: default;
}
/* On screens that are 959px or less as used on Wordalist */
@media screen and (max-width: 959px) {
  .ToolbarToggleItem,
  .ToolbarLink,
  .ToolbarText,
  .ToolbarButton {
    font-size: 1.2em;
    height: 2em;
  }

  .ToolbarLink svg,
  .ToolbarText svg,
  .ToolbarButton svg {
    width: 1.2em;
    height: 1.2em;
  }

  .ToolbarLink svg {
    /* Fix position due to parent having "display: inline" */
    position: relative;
    top: 0.2em;
  }

}
/* On screens that are 640px or less */
@media screen and (max-width: 640px) {
  .ToolbarButtonText {
    display: none;
  }
  .ToolbarButton svg {
    margin-right: 0;
  }
}
:root, .light, .light-theme {
  --black-a1: hsla(0, 0%, 0%, 0.012);
  --black-a2: hsla(0, 0%, 0%, 0.027);
  --black-a3: hsla(0, 0%, 0%, 0.047);
  --black-a4: hsla(0, 0%, 0%, 0.071);
  --black-a5: hsla(0, 0%, 0%, 0.090);
  --black-a6: hsla(0, 0%, 0%, 0.114);
  --black-a7: hsla(0, 0%, 0%, 0.141);
  --black-a8: hsla(0, 0%, 0%, 0.220);
  --black-a9: hsla(0, 0%, 0%, 0.439);
  --black-a10: hsla(0, 0%, 0%, 0.478);
  --black-a11: hsla(0, 0%, 0%, 0.565);
  --black-a12: hsla(0, 0%, 0%, 0.910);
}
:root, .light, .light-theme {
  --mauve-1: hsl(300, 20.0%, 99.0%);
  --mauve-2: hsl(300, 7.7%, 97.5%);
  --mauve-3: hsl(294, 5.5%, 95.3%);
  --mauve-4: hsl(289, 4.7%, 93.3%);
  --mauve-5: hsl(283, 4.4%, 91.3%);
  --mauve-6: hsl(278, 4.1%, 89.1%);
  --mauve-7: hsl(271, 3.9%, 86.3%);
  --mauve-8: hsl(255, 3.7%, 78.8%);
  --mauve-9: hsl(252, 4.0%, 57.3%);
  --mauve-10: hsl(253, 3.5%, 53.5%);
  --mauve-11: hsl(252, 4.0%, 44.8%);
  --mauve-12: hsl(260, 25.0%, 11.0%);
}
:root, .light, .light-theme {
  --violet-1: hsl(255, 65.0%, 99.4%);
  --violet-2: hsl(252, 100%, 99.0%);
  --violet-3: hsl(252, 96.9%, 97.4%);
  --violet-4: hsl(252, 91.5%, 95.5%);
  --violet-5: hsl(252, 85.1%, 93.0%);
  --violet-6: hsl(252, 77.8%, 89.4%);
  --violet-7: hsl(252, 71.0%, 83.7%);
  --violet-8: hsl(252, 68.6%, 76.3%);
  --violet-9: hsl(252, 56.0%, 57.5%);
  --violet-10: hsl(251, 48.1%, 53.5%);
  --violet-11: hsl(250, 43.0%, 48.0%);
  --violet-12: hsl(254, 60.0%, 18.5%);
}
:root, .light, .light-theme {
  --purple-1: hsl(280, 65.0%, 99.4%);
  --purple-2: hsl(276, 100%, 99.0%);
  --purple-3: hsl(276, 83.1%, 97.0%);
  --purple-4: hsl(275, 76.4%, 94.7%);
  --purple-5: hsl(275, 70.8%, 91.8%);
  --purple-6: hsl(274, 65.4%, 87.8%);
  --purple-7: hsl(273, 61.0%, 81.7%);
  --purple-8: hsl(272, 60.0%, 73.5%);
  --purple-9: hsl(272, 51.0%, 54.0%);
  --purple-10: hsl(272, 46.8%, 50.3%);
  --purple-11: hsl(272, 50.0%, 45.8%);
  --purple-12: hsl(272, 66.0%, 16.0%);
}
:root, .light, .light-theme {
  --plum-1: hsl(292, 90.0%, 99.4%);
  --plum-2: hsl(300, 100%, 98.6%);
  --plum-3: hsl(299, 71.2%, 96.4%);
  --plum-4: hsl(299, 62.0%, 93.8%);
  --plum-5: hsl(298, 56.1%, 90.5%);
  --plum-6: hsl(296, 51.3%, 85.8%);
  --plum-7: hsl(295, 48.2%, 78.9%);
  --plum-8: hsl(292, 47.7%, 70.8%);
  --plum-9: hsl(292, 45.0%, 51.0%);
  --plum-10: hsl(292, 50.2%, 46.9%);
  --plum-11: hsl(292, 60.0%, 42.5%);
  --plum-12: hsl(291, 66.0%, 14.0%);
}
:root, .light, .light-theme {
  --gray-1: hsl(0, 0%, 99.0%);
  --gray-2: hsl(0, 0%, 97.3%);
  --gray-3: hsl(0, 0%, 95.1%);
  --gray-4: hsl(0, 0%, 93.0%);
  --gray-5: hsl(0, 0%, 90.9%);
  --gray-6: hsl(0, 0%, 88.7%);
  --gray-7: hsl(0, 0%, 85.8%);
  --gray-8: hsl(0, 0%, 78.0%);
  --gray-9: hsl(0, 0%, 56.1%);
  --gray-10: hsl(0, 0%, 52.3%);
  --gray-11: hsl(0, 0%, 43.5%);
  --gray-12: hsl(0, 0%, 9.0%);
}
:root, .light, .light-theme {
  --blue-1: hsl(206, 100%, 99.2%);
  --blue-2: hsl(210, 100%, 98.0%);
  --blue-3: hsl(209, 100%, 96.5%);
  --blue-4: hsl(210, 98.8%, 94.0%);
  --blue-5: hsl(209, 95.0%, 90.1%);
  --blue-6: hsl(209, 81.2%, 84.5%);
  --blue-7: hsl(208, 77.5%, 76.9%);
  --blue-8: hsl(206, 81.9%, 65.3%);
  --blue-9: hsl(206, 100%, 50.0%);
  --blue-10: hsl(208, 100%, 47.3%);
  --blue-11: hsl(211, 100%, 43.2%);
  --blue-12: hsl(211, 100%, 15.0%);
}
:root, .light, .light-theme {
  --green-1: hsl(136, 50.0%, 98.9%);
  --green-2: hsl(138, 62.5%, 96.9%);
  --green-3: hsl(139, 55.2%, 94.5%);
  --green-4: hsl(140, 48.7%, 91.0%);
  --green-5: hsl(141, 43.7%, 86.0%);
  --green-6: hsl(143, 40.3%, 79.0%);
  --green-7: hsl(146, 38.5%, 69.0%);
  --green-8: hsl(151, 40.2%, 54.1%);
  --green-9: hsl(151, 55.0%, 41.5%);
  --green-10: hsl(152, 57.5%, 37.6%);
  --green-11: hsl(153, 67.0%, 28.5%);
  --green-12: hsl(155, 40.0%, 14.0%);
}
.ExploreSectionsToolbarRoot {
  background-color: var(--blue-6);
}
.ExploreSectionsToolbarRoot .ToolbarButton {
  background-color: var(--green-9);
}
.ExploreSectionsToolbarRoot .ToolbarButton:hover {
  background-color: var(--green-10);
}
/* Disabled button */
.ExploreSectionsToolbarRoot .ToolbarButton:disabled,
.ExploreSectionsToolbarRoot .ToolbarButton[disabled],
.ExploreSectionsToolbarRoot .ToolbarButton:disabled:hover,
.ExploreSectionsToolbarRoot .ToolbarButton[disabled]:hover{
  background-color: var(--gray-9);
  cursor: default;
}
.HeadingPage {
  padding: 10px;
  border-radius: 20px;
  background-color: var(--blue-4);
  text-align: center;
  color: var(--black-a11);
}
:root, .light, .light-theme {
  --black-a1: hsla(0, 0%, 0%, 0.012);
  --black-a2: hsla(0, 0%, 0%, 0.027);
  --black-a3: hsla(0, 0%, 0%, 0.047);
  --black-a4: hsla(0, 0%, 0%, 0.071);
  --black-a5: hsla(0, 0%, 0%, 0.090);
  --black-a6: hsla(0, 0%, 0%, 0.114);
  --black-a7: hsla(0, 0%, 0%, 0.141);
  --black-a8: hsla(0, 0%, 0%, 0.220);
  --black-a9: hsla(0, 0%, 0%, 0.439);
  --black-a10: hsla(0, 0%, 0%, 0.478);
  --black-a11: hsla(0, 0%, 0%, 0.565);
  --black-a12: hsla(0, 0%, 0%, 0.910);
}
:root, .light, .light-theme {
  --mauve-1: hsl(300, 20.0%, 99.0%);
  --mauve-2: hsl(300, 7.7%, 97.5%);
  --mauve-3: hsl(294, 5.5%, 95.3%);
  --mauve-4: hsl(289, 4.7%, 93.3%);
  --mauve-5: hsl(283, 4.4%, 91.3%);
  --mauve-6: hsl(278, 4.1%, 89.1%);
  --mauve-7: hsl(271, 3.9%, 86.3%);
  --mauve-8: hsl(255, 3.7%, 78.8%);
  --mauve-9: hsl(252, 4.0%, 57.3%);
  --mauve-10: hsl(253, 3.5%, 53.5%);
  --mauve-11: hsl(252, 4.0%, 44.8%);
  --mauve-12: hsl(260, 25.0%, 11.0%);
}
:root, .light, .light-theme {
  --violet-1: hsl(255, 65.0%, 99.4%);
  --violet-2: hsl(252, 100%, 99.0%);
  --violet-3: hsl(252, 96.9%, 97.4%);
  --violet-4: hsl(252, 91.5%, 95.5%);
  --violet-5: hsl(252, 85.1%, 93.0%);
  --violet-6: hsl(252, 77.8%, 89.4%);
  --violet-7: hsl(252, 71.0%, 83.7%);
  --violet-8: hsl(252, 68.6%, 76.3%);
  --violet-9: hsl(252, 56.0%, 57.5%);
  --violet-10: hsl(251, 48.1%, 53.5%);
  --violet-11: hsl(250, 43.0%, 48.0%);
  --violet-12: hsl(254, 60.0%, 18.5%);
}
:root, .light, .light-theme {
  --purple-1: hsl(280, 65.0%, 99.4%);
  --purple-2: hsl(276, 100%, 99.0%);
  --purple-3: hsl(276, 83.1%, 97.0%);
  --purple-4: hsl(275, 76.4%, 94.7%);
  --purple-5: hsl(275, 70.8%, 91.8%);
  --purple-6: hsl(274, 65.4%, 87.8%);
  --purple-7: hsl(273, 61.0%, 81.7%);
  --purple-8: hsl(272, 60.0%, 73.5%);
  --purple-9: hsl(272, 51.0%, 54.0%);
  --purple-10: hsl(272, 46.8%, 50.3%);
  --purple-11: hsl(272, 50.0%, 45.8%);
  --purple-12: hsl(272, 66.0%, 16.0%);
}
:root, .light, .light-theme {
  --plum-1: hsl(292, 90.0%, 99.4%);
  --plum-2: hsl(300, 100%, 98.6%);
  --plum-3: hsl(299, 71.2%, 96.4%);
  --plum-4: hsl(299, 62.0%, 93.8%);
  --plum-5: hsl(298, 56.1%, 90.5%);
  --plum-6: hsl(296, 51.3%, 85.8%);
  --plum-7: hsl(295, 48.2%, 78.9%);
  --plum-8: hsl(292, 47.7%, 70.8%);
  --plum-9: hsl(292, 45.0%, 51.0%);
  --plum-10: hsl(292, 50.2%, 46.9%);
  --plum-11: hsl(292, 60.0%, 42.5%);
  --plum-12: hsl(291, 66.0%, 14.0%);
}
:root, .light, .light-theme {
  --gray-1: hsl(0, 0%, 99.0%);
  --gray-2: hsl(0, 0%, 97.3%);
  --gray-3: hsl(0, 0%, 95.1%);
  --gray-4: hsl(0, 0%, 93.0%);
  --gray-5: hsl(0, 0%, 90.9%);
  --gray-6: hsl(0, 0%, 88.7%);
  --gray-7: hsl(0, 0%, 85.8%);
  --gray-8: hsl(0, 0%, 78.0%);
  --gray-9: hsl(0, 0%, 56.1%);
  --gray-10: hsl(0, 0%, 52.3%);
  --gray-11: hsl(0, 0%, 43.5%);
  --gray-12: hsl(0, 0%, 9.0%);
}
.CustomSelectionsToolbarRoot {
  background-color: var(--purple-6);
}
:root, .light, .light-theme {
  --black-a1: hsla(0, 0%, 0%, 0.012);
  --black-a2: hsla(0, 0%, 0%, 0.027);
  --black-a3: hsla(0, 0%, 0%, 0.047);
  --black-a4: hsla(0, 0%, 0%, 0.071);
  --black-a5: hsla(0, 0%, 0%, 0.090);
  --black-a6: hsla(0, 0%, 0%, 0.114);
  --black-a7: hsla(0, 0%, 0%, 0.141);
  --black-a8: hsla(0, 0%, 0%, 0.220);
  --black-a9: hsla(0, 0%, 0%, 0.439);
  --black-a10: hsla(0, 0%, 0%, 0.478);
  --black-a11: hsla(0, 0%, 0%, 0.565);
  --black-a12: hsla(0, 0%, 0%, 0.910);
}
:root, .light, .light-theme {
  --green-1: hsl(136, 50.0%, 98.9%);
  --green-2: hsl(138, 62.5%, 96.9%);
  --green-3: hsl(139, 55.2%, 94.5%);
  --green-4: hsl(140, 48.7%, 91.0%);
  --green-5: hsl(141, 43.7%, 86.0%);
  --green-6: hsl(143, 40.3%, 79.0%);
  --green-7: hsl(146, 38.5%, 69.0%);
  --green-8: hsl(151, 40.2%, 54.1%);
  --green-9: hsl(151, 55.0%, 41.5%);
  --green-10: hsl(152, 57.5%, 37.6%);
  --green-11: hsl(153, 67.0%, 28.5%);
  --green-12: hsl(155, 40.0%, 14.0%);
}
:root, .light, .light-theme {
  --mauve-1: hsl(300, 20.0%, 99.0%);
  --mauve-2: hsl(300, 7.7%, 97.5%);
  --mauve-3: hsl(294, 5.5%, 95.3%);
  --mauve-4: hsl(289, 4.7%, 93.3%);
  --mauve-5: hsl(283, 4.4%, 91.3%);
  --mauve-6: hsl(278, 4.1%, 89.1%);
  --mauve-7: hsl(271, 3.9%, 86.3%);
  --mauve-8: hsl(255, 3.7%, 78.8%);
  --mauve-9: hsl(252, 4.0%, 57.3%);
  --mauve-10: hsl(253, 3.5%, 53.5%);
  --mauve-11: hsl(252, 4.0%, 44.8%);
  --mauve-12: hsl(260, 25.0%, 11.0%);
}
:root, .light, .light-theme {
  --violet-1: hsl(255, 65.0%, 99.4%);
  --violet-2: hsl(252, 100%, 99.0%);
  --violet-3: hsl(252, 96.9%, 97.4%);
  --violet-4: hsl(252, 91.5%, 95.5%);
  --violet-5: hsl(252, 85.1%, 93.0%);
  --violet-6: hsl(252, 77.8%, 89.4%);
  --violet-7: hsl(252, 71.0%, 83.7%);
  --violet-8: hsl(252, 68.6%, 76.3%);
  --violet-9: hsl(252, 56.0%, 57.5%);
  --violet-10: hsl(251, 48.1%, 53.5%);
  --violet-11: hsl(250, 43.0%, 48.0%);
  --violet-12: hsl(254, 60.0%, 18.5%);
}
:root, .light, .light-theme {
  --blue-1: hsl(206, 100%, 99.2%);
  --blue-2: hsl(210, 100%, 98.0%);
  --blue-3: hsl(209, 100%, 96.5%);
  --blue-4: hsl(210, 98.8%, 94.0%);
  --blue-5: hsl(209, 95.0%, 90.1%);
  --blue-6: hsl(209, 81.2%, 84.5%);
  --blue-7: hsl(208, 77.5%, 76.9%);
  --blue-8: hsl(206, 81.9%, 65.3%);
  --blue-9: hsl(206, 100%, 50.0%);
  --blue-10: hsl(208, 100%, 47.3%);
  --blue-11: hsl(211, 100%, 43.2%);
  --blue-12: hsl(211, 100%, 15.0%);
}
:root, .light, .light-theme {
  --red-1: hsl(359, 100%, 99.4%);
  --red-2: hsl(359, 100%, 98.6%);
  --red-3: hsl(360, 100%, 96.8%);
  --red-4: hsl(360, 97.9%, 94.8%);
  --red-5: hsl(360, 90.2%, 91.9%);
  --red-6: hsl(360, 81.7%, 87.8%);
  --red-7: hsl(359, 74.2%, 81.7%);
  --red-8: hsl(359, 69.5%, 74.3%);
  --red-9: hsl(358, 75.0%, 59.0%);
  --red-10: hsl(358, 69.4%, 55.2%);
  --red-11: hsl(358, 65.0%, 48.7%);
  --red-12: hsl(354, 50.0%, 14.6%);
}
:root {
  --Dialogcontent-max-width: 1050px;
  --DialogContent-height: 85vh;
  --DialogContent-padding-top: 25px;
  --DialogContent-padding-bottom: 25px;
  --DialogContent-padding-left: 25px;
  --DialogContent-padding-right: 25px;
  --DialogTitle-padding: 0px;
  --DialogTitle-font-size: 17px;
  --ButtonGroup-margin-top: 25px;
  --Button-height: 35px;
  --IconButton-size: 25px;
  --Label-width: 300px;
  --Fieldset_ListItem-font-size: 15px;

  --Dialogcontent-max-width-mobile: 100vw;
  --DialogContent-height-mobile: 100vh;
  --DialogContent-padding-top-mobile: 30px;
  --DialogContent-padding-bottom-mobile: 50px;
  --DialogContent-padding-left-mobile: 0px;
  --DialogContent-padding-right-mobile: 0px;
  --DialogTitle-padding-mobile: 10px;
  --DialogTitle-font-size-mobile: 30px;
  --ButtonGroup-margin-top-mobile: 5px;
  --Button-height-mobile: 50px;
  --IconButton-size-mobile: 40px;
  --Label-width-mobile: calc(50vw - 20px - 20px - 20px);
  --Fieldset_ListItem-font-size-mobile: 1em;

  --Input-height: 35px;
}
/* reset */
/*button,
fieldset,
input {
  all: unset;
}*/
.Fieldset,
.Input {
  all: unset;
}
.DialogOverlay {
  background-color: var(--black-a9);
  position: fixed;
  inset: 0;
  animation: overlayShow 150ms cubic-bezier(0.16, 1, 0.3, 1);
  z-index: 9999; /* Fix */
}
.DialogOverlay.Alert {
  z-index: 10000; /* Fix */
}
.DialogContent {
  background-color: white;
  border-radius: 6px;
  box-shadow: hsl(206 22% 7% / 35%) 0px 10px 38px -10px, hsl(206 22% 7% / 20%) 0px 10px 20px -15px;
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 90vw;
  max-width: var(--Dialogcontent-max-width);
  max-height: var(--DialogContent-height);
  padding: var(--DialogContent-padding-top) var(--DialogContent-padding-right) var(--DialogContent-padding-bottom)
    var(--DialogContent-padding-left);
  animation: contentShow 150ms cubic-bezier(0.16, 1, 0.3, 1);
  z-index: 10000; /* Fix overlap */
}
.DialogOverlay.Alert .DialogContent {
  z-index: 10001; /* Fix overlap */
}
.DialogContent:focus {
  outline: none;
}
.DialogTitle {
  margin: 0;
  padding: var(--DialogTitle-padding);
  font-weight: 500;
  color: var(--mauve-12);
  font-size: var(--DialogTitle-font-size);
  /* Dealing with long titles */
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: calc(var(--Dialogcontent-max-width) - 50px);
  white-space: nowrap;
}
.DialogContentScroll {
  max-height: calc(
    var(--DialogContent-height) -
    var(--DialogContent-padding-top) -
    var(--DialogContent-padding-bottom) -
    var(--DialogTitle-padding) * 2 -
    var(--DialogTitle-font-size) -
    var(--ButtonGroup-margin-top) -
    var(--Button-height));
  overflow: scroll;
  padding-left: 10px;
  padding-right: 10px;
}
.DialogDescription {
  margin: 10px 0 20px;
  color: var(--mauve-11);
  font-size: 15px;
  line-height: 1.5;
}
.ButtonGroup {
  display: flex;
  margin-top: var(--ButtonGroup-margin-top);
  justify-content: flex-end;
}
.FieldsetTitle {
  width: 100%;
  text-align: center;
  font-size: 1.1em;
  margin: 10px 0;
}
.Fieldset .ButtonGroup {
  display: inline-flex;
  width: 100%;
  gap: 10px;
  flex: 1;
}
.DialogContent .Button {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  padding: 0 15px;
  font-size: 15px;
  line-height: 1;
  font-weight: 500;
  height: var(--Button-height);
  box-shadow: none;
}
.Button.violet {
  background-color: white;
  color: var(--violet-11);
  box-shadow: 0 2px 10px var(--black-a7);
}
.Button.violet:hover {
  background-color: var(--mauve-3);
}
.Button.violet:focus {
  box-shadow: 0 0 0 2px black;
}
.Button.green {
  background-color: var(--green-4);
  color: var(--green-11);
}
.Button.green:hover {
  background-color: var(--green-5);
}
.Button.green:focus {
  box-shadow: 0 0 0 2px var(--green-7);
}
.Button.mauve {
  background-color: var(--mauve-4);
  color: var(--mauve-11);
}
.Button.mauve:hover {
  background-color: var(--mauve-5);
}
.Button.mauve:focus {
  box-shadow: 0 0 0 2px var(--mauve-7);
}
.Button.blue {
  background-color: var(--blue-4);
  color: var(--blue-11);
}
.Button.blue:hover {
  background-color: var(--blue-5);
}
.Button.blue:focus {
  box-shadow: 0 0 0 2px var(--blue-7);
}
.ButtonGroup .Button {
  margin-left: 10px;
}
/* Button next to field */
.Fieldset .Button {
  border-radius: 50px;
}
.Fieldset .Button:disabled,
.Fieldset .Button[disabled],
.Fieldset .Button:disabled:hover,
.Fieldset .Button[disabled]:hover,
.Fieldset .Button:disabled:focus,
.Fieldset .Button[disabled]:focus {
  background-color: var(--gray-7);
  color: var(--gray-9);
  cursor: default;
  box-shadow: none;
  border: none;
}
/* Buttons as the only field */
.Fieldset .ButtonGroup .Button {
  margin: 0;
  display: inline-flex;
}
.IconButton {
  all: unset;
}
.IconButton {
  font-family: inherit;
  border-radius: 100%;
  height: var(--IconButton-size);
  width: var(--IconButton-size);
  display: inline-flex;
  align-items: center;
  justify-content: center;
  color: var(--violet-11);
  position: absolute;
  top: 10px;
  right: 10px;
}
.IconButton:hover {
  background-color: var(--violet-4);
}
.IconButton:focus {
  box-shadow: 0 0 0 2px var(--violet-7);
}
.MultiFieldset {
  display: block;
  margin-bottom: 15px;
  margin-right: 10px;
}
.Fieldset {
  display: flex;
  gap: 20px;
  align-items: center;
  margin-bottom: 15px;
  margin-right: 10px;
}
.MultiFieldset .Fieldset {
  margin: 0 0 15px;
  border-bottom: none;
}
.Fieldset .ButtonGroup {
  margin: 0;
}
.Label {
  font-size: 15px;
  color: var(--violet-11);
  width: var(--Label-width);
  text-align: right;
  word-wrap: break-word;
  hyphens: auto;
}
.Input,
.Textarea {
  width: 100%;
  flex: 1;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  padding: 0 10px;
  font-size: 15px;
  line-height: 1;
  color: var(--violet-11);
  box-shadow: 0 0 0 1px var(--violet-7);
}
.Input {
  height: var(--Input-height);
}
.Input:focus,
.Textarea:focus {
  box-shadow: 0 0 0 2px var(--violet-8);
}
.Textarea {
  resize: none;
  padding: 10px;
  height: 50vh;
}
.Textarea:focus {
  color: var(--violet-11);
}
.TextareaCode {
  font-family: monospace;
  font-size: 0.8em;
}
.TextareaSmall {
  height: calc(var(--Input-height) * 5);
}
.SyncExercisesList,
.SyncSectionsList {
  width: 100%;
  flex: 1;
  margin: 0;
}
.SyncExercisesList {
  flex-wrap: wrap;
  padding: 10px;
  border-radius: 20px;
  box-shadow: 0 0 0 1px var(--violet-7);
}
.SyncSectionsList {
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
  padding: 5px;
  background: none;
}
.SyncExercisesList li,
.SyncSectionsList li {
  list-style-type: none;
  padding: 5px;
  font-size: var(--Fieldset_ListItem-font-size);
  line-height: 1;
  color: var(--violet-11);
  box-shadow: 0 0 0 1px var(--violet-7);
  background-color: var(--blue-5);
  text-align: center;
}
.SyncExercisesList li {
  margin: 0 0 10px;
  border-radius: 10px;
  background-color: var(--blue-2);
}
.SyncSectionsList li {
  flex-grow: 1;
  margin: 0;
  border-radius: 5px;
  background-color: var(--blue-5);
}
.SyncExercisesList li:nth-last-child(1) {
  margin: 0;
}
.SyncExerciseName {
  font-weight: bold;
}
.SyncExerciseNameDiffer {
  color: var(--red-10);
}
@keyframes overlayShow {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}
@keyframes contentShow {
  from {
    opacity: 0;
    transform: translate(-50%, -48%) scale(0.96);
  }
  to {
    opacity: 1;
    transform: translate(-50%, -50%) scale(1);
  }
}
/* Forms */
.SwitchRoot {
  all: unset;
}
.SwitchRoot {
  margin-bottom: 10px;
  width: 42px;
  height: 25px;
  background-color: var(--black-a9);
  border-radius: 9999px;
  position: relative;
  box-shadow: 0 2px 10px var(--black-a7);
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
.SwitchRoot:focus {
  box-shadow: 0 0 0 2px black;
}
.SwitchRoot[data-state='checked'] {
  background-color: black;
}
.SwitchThumb {
  display: block;
  width: 21px;
  height: 21px;
  background-color: white;
  border-radius: 9999px;
  box-shadow: 0 2px 2px var(--black-a7);
  transition: transform 100ms;
  transform: translateX(2px);
  will-change: transform;
}
.SwitchThumb[data-state='checked'] {
  transform: translateX(19px);
}
.Fieldset.Switch .Label {
  font-size: 15px;
  line-height: 1;
  width: 100%;
  flex: 1;
  display: inline-flex;
  align-items: center;
  justify-content: right;
}
/* Radio */
/* reset */
/*button {
  all: unset;
}*/
.RadioGroupRoot {
  margin-bottom: 10px;
  display: flex;
  flex-direction: column;
  gap: 10px;
}
.RadioGroupItem {
  all: unset;
}
.RadioGroupItem {
  background-color: white;
  width: 25px;
  height: 25px;
  border-radius: 100%;
  box-shadow: 0 2px 10px var(--black-a7);
}
.RadioGroupItem:hover {
  background-color: var(--violet-3);
}
.RadioGroupItem:focus {
  box-shadow: 0 0 0 2px black;
}
.RadioGroupIndicator {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  position: relative;
}
.RadioGroupIndicator::after {
  content: '';
  display: block;
  width: 11px;
  height: 11px;
  border-radius: 50%;
  background-color: var(--violet-11);
}
.RadioGroupRoot .Label {
  width: calc(100% - 25px);
  text-align: left;
  padding-left: 10px;
}
/* On screens that are 959px or less */
@media screen and (max-width: 959px) {
  .DialogContent {
    margin: 0;
    max-width: var(--Dialogcontent-max-width-mobile);
    width: 100vw;
    max-height: 100vh;
    height: var(--DialogContent-height-mobile);
    border-radius: 0;
    padding: var(--DialogContent-padding-top-mobile) var(--DialogContent-padding-right-mobile)
      var(--DialogContent-padding-bottom-mobile) var(--DialogContent-padding-left-mobile);
  }

  .IconButton {
    top: calc(
      var(--DialogContent-padding-top-mobile) +
      var(--DialogTitle-padding-mobile) / 2
    );
    height: var(--IconButton-size-mobile);
    width: var(--IconButton-size-mobile);
  }

  .IconButton svg {
    width: 40px;
    height: 40px;
  }

  .DialogTitle {
    max-width: 100vw;
    padding: var(--DialogTitle-padding-mobile);
    font-size: var(--DialogTitle-font-size-mobile);
    text-align: center;
  }

  .DialogDescription {
    padding: 10px calc(var(--IconButton-size-mobile) + 10px) 10px 20px;
    text-align: center;
    font-size: 1.2em;
  }

  .Fieldset, .MultiFieldset {
    margin: 20px;
    padding: 0;
    font-size: 1.2em;
    border-bottom: 1px var(--mauve-9) dashed;
  }

  .MultiFieldset .Fieldset {
    margin: 0 0 20px;
    border-bottom: none;
  }

  .Fieldset .Input {
    font-size: 1.2em;
    height: 2em;
  }

  .Label,
  .Fieldset.Switch .Label {
    font-size: 1.2em;
    width: var(--Label-width-mobile);
  }

  .Fieldset.Switch .Label {
    flex: none;
  }

  .ButtonGroup {
    justify-content: center;
    margin-top: var(--ButtonGroup-margin-top-mobile);
  }

  .Fieldset .ButtonGroup {
    justify-content: right;
    margin: 0;
  }

  .Button {
    font-size: 1.2em;
    height: var(--Button-height-mobile);
    text-align: center;
  }

  .SyncExercisesList li,
  .SyncSectionsList li {
    font-size: var(--Fieldset_ListItem-font-size-mobile);
  }

  .DialogContentScroll {
    max-height: calc(
      var(--DialogContent-height-mobile) -
      var(--DialogContent-padding-top-mobile) -
      var(--DialogContent-padding-bottom-mobile) -
      var(--DialogTitle-padding-mobile) * 2 -
      var(--DialogTitle-font-size-mobile) -
      var(--ButtonGroup-margin-top-mobile) -
      var(--Button-height-mobile) - 2px);
    overflow: scroll;
  }

}
:root, .light, .light-theme {
  --black-a1: hsla(0, 0%, 0%, 0.012);
  --black-a2: hsla(0, 0%, 0%, 0.027);
  --black-a3: hsla(0, 0%, 0%, 0.047);
  --black-a4: hsla(0, 0%, 0%, 0.071);
  --black-a5: hsla(0, 0%, 0%, 0.090);
  --black-a6: hsla(0, 0%, 0%, 0.114);
  --black-a7: hsla(0, 0%, 0%, 0.141);
  --black-a8: hsla(0, 0%, 0%, 0.220);
  --black-a9: hsla(0, 0%, 0%, 0.439);
  --black-a10: hsla(0, 0%, 0%, 0.478);
  --black-a11: hsla(0, 0%, 0%, 0.565);
  --black-a12: hsla(0, 0%, 0%, 0.910);
}
:root, .light, .light-theme {
  --blue-1: hsl(206, 100%, 99.2%);
  --blue-2: hsl(210, 100%, 98.0%);
  --blue-3: hsl(209, 100%, 96.5%);
  --blue-4: hsl(210, 98.8%, 94.0%);
  --blue-5: hsl(209, 95.0%, 90.1%);
  --blue-6: hsl(209, 81.2%, 84.5%);
  --blue-7: hsl(208, 77.5%, 76.9%);
  --blue-8: hsl(206, 81.9%, 65.3%);
  --blue-9: hsl(206, 100%, 50.0%);
  --blue-10: hsl(208, 100%, 47.3%);
  --blue-11: hsl(211, 100%, 43.2%);
  --blue-12: hsl(211, 100%, 15.0%);
}
:root, .light, .light-theme {
  --gray-1: hsl(0, 0%, 99.0%);
  --gray-2: hsl(0, 0%, 97.3%);
  --gray-3: hsl(0, 0%, 95.1%);
  --gray-4: hsl(0, 0%, 93.0%);
  --gray-5: hsl(0, 0%, 90.9%);
  --gray-6: hsl(0, 0%, 88.7%);
  --gray-7: hsl(0, 0%, 85.8%);
  --gray-8: hsl(0, 0%, 78.0%);
  --gray-9: hsl(0, 0%, 56.1%);
  --gray-10: hsl(0, 0%, 52.3%);
  --gray-11: hsl(0, 0%, 43.5%);
  --gray-12: hsl(0, 0%, 9.0%);
}
:root, .light, .light-theme {
  --green-1: hsl(136, 50.0%, 98.9%);
  --green-2: hsl(138, 62.5%, 96.9%);
  --green-3: hsl(139, 55.2%, 94.5%);
  --green-4: hsl(140, 48.7%, 91.0%);
  --green-5: hsl(141, 43.7%, 86.0%);
  --green-6: hsl(143, 40.3%, 79.0%);
  --green-7: hsl(146, 38.5%, 69.0%);
  --green-8: hsl(151, 40.2%, 54.1%);
  --green-9: hsl(151, 55.0%, 41.5%);
  --green-10: hsl(152, 57.5%, 37.6%);
  --green-11: hsl(153, 67.0%, 28.5%);
  --green-12: hsl(155, 40.0%, 14.0%);
}
:root, .light, .light-theme {
  --mauve-1: hsl(300, 20.0%, 99.0%);
  --mauve-2: hsl(300, 7.7%, 97.5%);
  --mauve-3: hsl(294, 5.5%, 95.3%);
  --mauve-4: hsl(289, 4.7%, 93.3%);
  --mauve-5: hsl(283, 4.4%, 91.3%);
  --mauve-6: hsl(278, 4.1%, 89.1%);
  --mauve-7: hsl(271, 3.9%, 86.3%);
  --mauve-8: hsl(255, 3.7%, 78.8%);
  --mauve-9: hsl(252, 4.0%, 57.3%);
  --mauve-10: hsl(253, 3.5%, 53.5%);
  --mauve-11: hsl(252, 4.0%, 44.8%);
  --mauve-12: hsl(260, 25.0%, 11.0%);
}
:root, .light, .light-theme {
  --plum-1: hsl(292, 90.0%, 99.4%);
  --plum-2: hsl(300, 100%, 98.6%);
  --plum-3: hsl(299, 71.2%, 96.4%);
  --plum-4: hsl(299, 62.0%, 93.8%);
  --plum-5: hsl(298, 56.1%, 90.5%);
  --plum-6: hsl(296, 51.3%, 85.8%);
  --plum-7: hsl(295, 48.2%, 78.9%);
  --plum-8: hsl(292, 47.7%, 70.8%);
  --plum-9: hsl(292, 45.0%, 51.0%);
  --plum-10: hsl(292, 50.2%, 46.9%);
  --plum-11: hsl(292, 60.0%, 42.5%);
  --plum-12: hsl(291, 66.0%, 14.0%);
}
:root, .light, .light-theme {
  --purple-1: hsl(280, 65.0%, 99.4%);
  --purple-2: hsl(276, 100%, 99.0%);
  --purple-3: hsl(276, 83.1%, 97.0%);
  --purple-4: hsl(275, 76.4%, 94.7%);
  --purple-5: hsl(275, 70.8%, 91.8%);
  --purple-6: hsl(274, 65.4%, 87.8%);
  --purple-7: hsl(273, 61.0%, 81.7%);
  --purple-8: hsl(272, 60.0%, 73.5%);
  --purple-9: hsl(272, 51.0%, 54.0%);
  --purple-10: hsl(272, 46.8%, 50.3%);
  --purple-11: hsl(272, 50.0%, 45.8%);
  --purple-12: hsl(272, 66.0%, 16.0%);
}
:root, .light, .light-theme {
  --red-1: hsl(359, 100%, 99.4%);
  --red-2: hsl(359, 100%, 98.6%);
  --red-3: hsl(360, 100%, 96.8%);
  --red-4: hsl(360, 97.9%, 94.8%);
  --red-5: hsl(360, 90.2%, 91.9%);
  --red-6: hsl(360, 81.7%, 87.8%);
  --red-7: hsl(359, 74.2%, 81.7%);
  --red-8: hsl(359, 69.5%, 74.3%);
  --red-9: hsl(358, 75.0%, 59.0%);
  --red-10: hsl(358, 69.4%, 55.2%);
  --red-11: hsl(358, 65.0%, 48.7%);
  --red-12: hsl(354, 50.0%, 14.6%);
}
:root, .light, .light-theme {
  --violet-1: hsl(255, 65.0%, 99.4%);
  --violet-2: hsl(252, 100%, 99.0%);
  --violet-3: hsl(252, 96.9%, 97.4%);
  --violet-4: hsl(252, 91.5%, 95.5%);
  --violet-5: hsl(252, 85.1%, 93.0%);
  --violet-6: hsl(252, 77.8%, 89.4%);
  --violet-7: hsl(252, 71.0%, 83.7%);
  --violet-8: hsl(252, 68.6%, 76.3%);
  --violet-9: hsl(252, 56.0%, 57.5%);
  --violet-10: hsl(251, 48.1%, 53.5%);
  --violet-11: hsl(250, 43.0%, 48.0%);
  --violet-12: hsl(254, 60.0%, 18.5%);
}
:root {
  --DialogCustomSelectionsStorage_DialogContent-max-width: 1000px;
}
.DialogCustomSelectionsStorage.DialogContent {
  max-width: var(--DialogCustomSelectionsStorage_DialogContent-max-width);
}
.DialogCustomSelectionsStorage .DialogTitle {
  max-width: calc(var(--DialogCustomSelectionsStorage_DialogContent-max-width) - 50px);
}
.HandleWrapper {
  height: 1rem;
  vertical-align: bottom;
  display: inline-block;
  margin-right: 0.5rem;
}
.HandleWrapper svg {
  width: 100%;
  height: 100%;
}
.DraggingRow {
  background: rgba(127, 207, 250, 0.3);
}
.SortableExercisesCollection,
.SortableCustomSelectionsCollection,
.SortableSectionsCollection {
  list-style-position: inside;
  padding-left: 0;
  margin: 0;
}
.SortableExercisesCollection {
  margin-right: 15px;
}
.SortableCustomSelectionsCollection {
  margin: 5px;
}
.SortableSectionsCollection {
  margin: 10px;
}
.SortableExercise,
.SortableCustomSelection,
.SortableSection {
  box-shadow: 0 2px 10px var(--black-a4);
  border-radius: 6px;
  list-style: none;
  padding: 0;
  margin: 0;
}
.SortableExercise {
  background-color: var(--purple-5);
  padding: 10px;
  margin-bottom: 20px;
}
.SortableExercise:last-child {
  margin-bottom: 10px;
}
.SortableCustomSelection {
  background-color: var(--violet-3);
  margin-bottom: 10px;
  padding: 5px;
}
.SortableCustomSelection:last-child {
  margin-bottom: 0;
}
.SortableSection {
  border-radius: 0;
  box-shadow: 0 2px 0 var(--black-a4);
  background-color: var(--mauve-1);
  margin-bottom: 5px;
  padding: 5px;
}
.SortableSection:last-child {
  margin-bottom: 0;
}
.SortableExercise svg,
.SortableCustomSelection svg,
.SortableSection svg {
  /* Fix position due to parent having "display: inline" */
  position: relative;
  top: 0.15em;
}
.SortableExercise svg:hover,
.SortableCustomSelection svg:hover,
.SortableSection svg:hover {
  cursor: grab;
}
.SortableExercise svg:active,
.SortableCustomSelection svg:active,
.SortableSection svg:active {
  cursor: grabbing;
}
.SortableItemButton {
  all: unset;
}
.SortableItemButton:hover,
.SortableItemButton:active,
.SortableItemButton svg:hover,
.SortableItemButton svg:active{
  cursor: pointer;
}
.FloatBarrier {
  clear: both;
}
.SortableItemButton {
  margin-left: 5px;
  background-color: var(--mauve-7);
  float: right;
  flex: 0 0 auto;
  color: var(--mauve-11);
  padding: 5px 10px;
  border-radius: 10px;
  display: inline-flex;
  font-size: 13px;
  line-height: 1;
  align-items: center;
  justify-content: center;
}
.CustomSelectionButtonGroup {
  float: right;
}
.CustomSelectionButtonGroup .SortableItemButton {
  float: none;
}
.SectionLastPractice,
.SectionPracticesToday,
.SectionPracticesTotal {
  margin-left: 5px;
  background-color: var(--mauve-7);
  color: var(--mauve-11);
  padding: 5px 10px;
  border-radius: 10px;
  display: inline-flex;
  font-size: 13px;
  line-height: 1;
}
.SortableItemButton {
  text-align: center;
  vertical-align: middle;
  padding: 3px 5px 3px 4px;
  color: var(--violet-9);
  background-color: transparent;
  display: inline;
}
.SortableItemButton.ButtonDelete {
  color: var(--red-10);
}
.SortableItemButton.ButtonAction {
  color: var(--green-10);
}
.SortableItemButton.ButtonAction.ButtonActive {
  color: var(--mauve-10);
}
.SortableItemButton svg {
  position: relative;
  top: 1px;
}
.SectionLastPractice {
  background-color: var(--mauve-7);
  color: var(--mauve-11);
}
.SectionPracticesToday {
  background-color: var(--green-6);
  color: var(--mauve-11);
}
.SectionPracticesTotal {
  float: right;
  background-color: var(--mauve-7);
  color: var(--mauve-11);
}
.SectionPracticesToday.NotPracticedToday{
  background-color: var(--mauve-7);
}
.CustomSelectionLink {
  background-color: transparent;
  color: var(--violet-11);
  justify-content: center;
  align-items: center;
  /* Maximum minimizing capabilities */
  /* display: inline-flex; */ /* Disabled for maximum resizing */
  display: inline; /* Allow resizing */
}
.CustomSelectionLink:hover {
  background-color: transparent;
  cursor: pointer;
}
/* On screens that are 959px or less as already used on Wordalist */
@media screen and (max-width: 959px) {

  .SortableExercisesCollection {
    margin-right: 0;
    font-size: 1.2em;
  }

  .SortableCustomSelectionsCollection {
    margin: 10px 0 0 30px;
  }

  .SortableSectionsCollection {
    margin: 10px 0 0 30px;
  }

  .SortableExercise {
    padding: 5px;
  }

  .SortableExercise:last-child {
    margin-bottom: 10px;
  }

  .SortableCustomSelection {
    padding: 10px;
  }

  .SortableCustomSelection:last-child {
    margin-bottom: 10px;
  }

  .SortableSection {
    padding: 10px;
  }

  .SortableSection:last-child {
    margin-bottom: 10px;
  }

  .SortableExercise svg,
  .SortableCustomSelection svg,
  .SortableSection svg {
    /* Fix position due to parent having "display: inline" */
    position: relative;
    top: 0.15em;
    width: 2em;
    height: 1em;
  }

  .CustomSelectionLink {
    margin-left: 10px;
  }

  .CustomSelectionLink svg {
    width: 1em;
    height: 1em;
    top: 0.2em;
  }

  .SortableItemButton {
    height: 1em;
    width: 2em;
    margin: 0 0 10px 20px;
  }

  .SortableItemButton svg {
    position: relative;
    top: -0.2em;
    width: 2em;
    height: 2em;
  }

  .CustomSelectionStatistics {
    margin-left: 40px;
  }

  .SectionLastPractice,
  .SectionPracticesToday,
  .SectionPracticesTotal {
    font-size: 0.8em;
  }

  /* Sorting doesn't work well on a touch screen.
  TODO: find solution to sorting issue on touch screen
  Until then, sorting is hidden on small screens.
  */
  .SortableExercise > span {
    margin-left: 10px;
  }

  [aria-roledescription='sortable'] {
    display: none;
  }

}
:root {
  --Dialogcontent-max-width: 1050px;
  --DialogContent-height: 85vh;
  --DialogContent-padding-top: 25px;
  --DialogContent-padding-bottom: 25px;
  --DialogContent-padding-left: 25px;
  --DialogContent-padding-right: 25px;
  --DialogTitle-padding: 0px;
  --DialogTitle-font-size: 17px;
  --ButtonGroup-margin-top: 25px;
  --Button-height: 35px;
  --IconButton-size: 25px;
  --Label-width: 300px;
  --Fieldset_ListItem-font-size: 15px;

  --Dialogcontent-max-width-mobile: 100vw;
  --DialogContent-height-mobile: 100vh;
  --DialogContent-padding-top-mobile: 30px;
  --DialogContent-padding-bottom-mobile: 50px;
  --DialogContent-padding-left-mobile: 0px;
  --DialogContent-padding-right-mobile: 0px;
  --DialogTitle-padding-mobile: 10px;
  --DialogTitle-font-size-mobile: 30px;
  --ButtonGroup-margin-top-mobile: 5px;
  --Button-height-mobile: 50px;
  --IconButton-size-mobile: 40px;
  --Label-width-mobile: calc(50vw - 20px - 20px - 20px);
  --Fieldset_ListItem-font-size-mobile: 1em;

  --Input-height: 35px;
}

:root {
  --Alert_Dialogcontent-max-width: calc(var(--Dialogcontent-max-width) * 0.8);
}

.Alert.DialogContent {
  max-width: var(--Alert_Dialogcontent-max-width);
}
:root, .light, .light-theme {
  --black-a1: hsla(0, 0%, 0%, 0.012);
  --black-a2: hsla(0, 0%, 0%, 0.027);
  --black-a3: hsla(0, 0%, 0%, 0.047);
  --black-a4: hsla(0, 0%, 0%, 0.071);
  --black-a5: hsla(0, 0%, 0%, 0.090);
  --black-a6: hsla(0, 0%, 0%, 0.114);
  --black-a7: hsla(0, 0%, 0%, 0.141);
  --black-a8: hsla(0, 0%, 0%, 0.220);
  --black-a9: hsla(0, 0%, 0%, 0.439);
  --black-a10: hsla(0, 0%, 0%, 0.478);
  --black-a11: hsla(0, 0%, 0%, 0.565);
  --black-a12: hsla(0, 0%, 0%, 0.910);
}
:root, .light, .light-theme {
  --green-1: hsl(136, 50.0%, 98.9%);
  --green-2: hsl(138, 62.5%, 96.9%);
  --green-3: hsl(139, 55.2%, 94.5%);
  --green-4: hsl(140, 48.7%, 91.0%);
  --green-5: hsl(141, 43.7%, 86.0%);
  --green-6: hsl(143, 40.3%, 79.0%);
  --green-7: hsl(146, 38.5%, 69.0%);
  --green-8: hsl(151, 40.2%, 54.1%);
  --green-9: hsl(151, 55.0%, 41.5%);
  --green-10: hsl(152, 57.5%, 37.6%);
  --green-11: hsl(153, 67.0%, 28.5%);
  --green-12: hsl(155, 40.0%, 14.0%);
}
:root, .light, .light-theme {
  --mauve-1: hsl(300, 20.0%, 99.0%);
  --mauve-2: hsl(300, 7.7%, 97.5%);
  --mauve-3: hsl(294, 5.5%, 95.3%);
  --mauve-4: hsl(289, 4.7%, 93.3%);
  --mauve-5: hsl(283, 4.4%, 91.3%);
  --mauve-6: hsl(278, 4.1%, 89.1%);
  --mauve-7: hsl(271, 3.9%, 86.3%);
  --mauve-8: hsl(255, 3.7%, 78.8%);
  --mauve-9: hsl(252, 4.0%, 57.3%);
  --mauve-10: hsl(253, 3.5%, 53.5%);
  --mauve-11: hsl(252, 4.0%, 44.8%);
  --mauve-12: hsl(260, 25.0%, 11.0%);
}
:root, .light, .light-theme {
  --slate-1: hsl(206, 30.0%, 98.8%);
  --slate-2: hsl(210, 16.7%, 97.6%);
  --slate-3: hsl(209, 13.3%, 95.3%);
  --slate-4: hsl(209, 12.2%, 93.2%);
  --slate-5: hsl(208, 11.7%, 91.1%);
  --slate-6: hsl(208, 11.3%, 88.9%);
  --slate-7: hsl(207, 11.1%, 85.9%);
  --slate-8: hsl(205, 10.7%, 78.0%);
  --slate-9: hsl(206, 6.0%, 56.1%);
  --slate-10: hsl(206, 5.8%, 52.3%);
  --slate-11: hsl(206, 6.0%, 43.5%);
  --slate-12: hsl(206, 24.0%, 9.0%);
}
:root, .light, .light-theme {
  --violet-1: hsl(255, 65.0%, 99.4%);
  --violet-2: hsl(252, 100%, 99.0%);
  --violet-3: hsl(252, 96.9%, 97.4%);
  --violet-4: hsl(252, 91.5%, 95.5%);
  --violet-5: hsl(252, 85.1%, 93.0%);
  --violet-6: hsl(252, 77.8%, 89.4%);
  --violet-7: hsl(252, 71.0%, 83.7%);
  --violet-8: hsl(252, 68.6%, 76.3%);
  --violet-9: hsl(252, 56.0%, 57.5%);
  --violet-10: hsl(251, 48.1%, 53.5%);
  --violet-11: hsl(250, 43.0%, 48.0%);
  --violet-12: hsl(254, 60.0%, 18.5%);
}
.ToastViewport {
  --viewport-padding: 25px;
  position: fixed;
  bottom: 0;
  right: 0;
  display: flex;
  flex-direction: column;
  padding: var(--viewport-padding);
  gap: 10px;
  width: 390px;
  max-width: 100vw;
  margin: 0;
  list-style: none;
  z-index: 2147483647;
  outline: none;
}
.ToastRoot {
  background-color: white;
  border-radius: 6px;
  box-shadow: hsl(206 22% 7% / 35%) 0px 10px 38px -10px, hsl(206 22% 7% / 20%) 0px 10px 20px -15px;
  padding: 15px;
  display: grid;
  grid-template-areas: 'title action' 'description action';
  grid-template-columns: auto max-content;
  column-gap: 15px;
  align-items: center;
}
.ToastRoot[data-state='open'] {
  animation: slideIn 150ms cubic-bezier(0.16, 1, 0.3, 1);
}
.ToastRoot[data-state='closed'] {
  animation: hide 100ms ease-in;
}
.ToastRoot[data-swipe='move'] {
  transform: translateX(var(--radix-toast-swipe-move-x));
}
.ToastRoot[data-swipe='cancel'] {
  transform: translateX(0);
  transition: transform 200ms ease-out;
}
.ToastRoot[data-swipe='end'] {
  animation: swipeOut 100ms ease-out;
}
.ToastRoot.NotificationWarn {
  background-color: #ffe4c6;
}
.ToastTitle.NotificationWarn, .ToastDescription.NotificationWarn {
  color: #6d4518;
}
.ToastRoot.NotificationErr {
  background-color: #ffc6c6;
}
.ToastTitle.NotificationErr, .ToastDescription.NotificationErr {
  color: #6d1818;
}
@keyframes hide {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}
@keyframes slideIn {
  from {
    transform: translateX(calc(100% + var(--viewport-padding)));
  }
  to {
    transform: translateX(0);
  }
}
@keyframes swipeOut {
  from {
    transform: translateX(var(--radix-toast-swipe-end-x));
  }
  to {
    transform: translateX(calc(100% + var(--viewport-padding)));
  }
}
.ToastTitle {
  grid-area: title;
  margin-bottom: 5px;
  font-weight: 500;
  color: var(--slate-12);
  font-size: 15px;
}
.ToastDescription {
  grid-area: description;
  margin: 0;
  color: var(--slate-11);
  font-size: 13px;
  line-height: 1.3;
}
.ToastAction {
  grid-area: action;
}
.Button {
  border-radius: 8px;
  border: 1px solid transparent;
  padding: 0.6em 1.2em;
  font-size: 1em;
  font-weight: 500;
  font-family: inherit;
  background-color: #1a1a1a;
  cursor: pointer;
  transition: border-color 0.25s;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}
.Button:hover {
  border-color: #646cff;
}
.Button:focus,
.Button:focus-visible {
  outline: 4px auto -webkit-focus-ring-color;
}
.Button.small {
  font-size: 12px;
  padding: 0 10px;
  line-height: 25px;
  height: 25px;
}
.Button.large {
  font-size: 15px;
  padding: 0 15px;
  line-height: 35px;
  height: 35px;
}
.Button.violet {
  background-color: white;
  color: var(--violet-11);
  box-shadow: 0 2px 10px var(--black-a7);
}
.Button.violet:hover {
  background-color: var(--mauve-3);
}
.Button.violet:focus {
  box-shadow: 0 0 0 2px black;
}
.Button.green {
  background-color: var(--green-2);
  color: var(--green-11);
  box-shadow: inset 0 0 0 1px var(--green-7);
}
.Button.green:hover {
  box-shadow: inset 0 0 0 1px var(--green-8);
}
.Button.green:focus {
  box-shadow: 0 0 0 2px var(--green-8);
}
:root, .light, .light-theme {
  --plum-1: hsl(292, 90.0%, 99.4%);
  --plum-2: hsl(300, 100%, 98.6%);
  --plum-3: hsl(299, 71.2%, 96.4%);
  --plum-4: hsl(299, 62.0%, 93.8%);
  --plum-5: hsl(298, 56.1%, 90.5%);
  --plum-6: hsl(296, 51.3%, 85.8%);
  --plum-7: hsl(295, 48.2%, 78.9%);
  --plum-8: hsl(292, 47.7%, 70.8%);
  --plum-9: hsl(292, 45.0%, 51.0%);
  --plum-10: hsl(292, 50.2%, 46.9%);
  --plum-11: hsl(292, 60.0%, 42.5%);
  --plum-12: hsl(291, 66.0%, 14.0%);
}
:root, .light, .light-theme {
  --purple-1: hsl(280, 65.0%, 99.4%);
  --purple-2: hsl(276, 100%, 99.0%);
  --purple-3: hsl(276, 83.1%, 97.0%);
  --purple-4: hsl(275, 76.4%, 94.7%);
  --purple-5: hsl(275, 70.8%, 91.8%);
  --purple-6: hsl(274, 65.4%, 87.8%);
  --purple-7: hsl(273, 61.0%, 81.7%);
  --purple-8: hsl(272, 60.0%, 73.5%);
  --purple-9: hsl(272, 51.0%, 54.0%);
  --purple-10: hsl(272, 46.8%, 50.3%);
  --purple-11: hsl(272, 50.0%, 45.8%);
  --purple-12: hsl(272, 66.0%, 16.0%);
}
.wle-page-exercise-sections-addition {
  margin-right: 10px;
  margin-top: 0;
  float: right;
  background-color: var(--purple-8);
  padding: 4px 15px 4px 5px;
  border-radius: 20px;
}
#wle-page-exercise-sections-toolbar-container {
  width: 100%;
}
#wle-top-bar-container,
.TopBarContainer {
  display: none;
}
/* On screens that are 959px or less as used on Wordalist */
@media screen and (max-width: 959px) {
  /* Hide original menu */
  #wle-bottom-menu-settings-item,
  #wle-personal-menu-selection-item,
  #wle-personal-menu-synchronization-item {
    display: none;
  }

  /* Show top bar */
  #wle-top-bar-container,
  .TopBarContainer {
    display: block;
  }

  .TopBarContainer {
    list-style: none inside none;
    position: fixed;
    top: 10px;
    right: 10px;
    padding: 0;
    margin: 0;
    text-align: center;
  }

  .TopBarContainer > li {
    margin: 0 0 10px;
  }

  .TopBarContainer > li a {
    color: var(--mauve-11);
    background-color: var(--purple-6);
    display: block;
    width: 80px;
    height: 80px;
    border-radius: 80px;
    position: relative;
    opacity: 0.7;
  }

  .TopBarContainer > li a svg {
    position: absolute;
    top: 15px;
    left: 15px;
    width: 50px;
    height: 50px;
    color: var(--purple-9);
  }

  .TopBarContainer.ScrollMinimize {
    top: 5px;
    right: 5px;
  }

  .TopBarContainer.ScrollMinimize > li {
    margin: 0 0 5px;
  }

  .TopBarContainer.ScrollMinimize > li a {
    width: 30px;
    height: 30px;
    border-radius: 40px;
  }

  .TopBarContainer.ScrollMinimize > li a svg {
    top: 5px;
    left: 5px;
    width: 20px;
    height: 20px;
  }

} `);

(function () {
  'use strict';

  var __defProp = Object.defineProperty;
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  var __publicField = (obj, key, value) => {
    __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
    return value;
  };
  var _a;
  var n, l$1, u$1, i$1, o$2, r$1, f$1, e$1, c$1 = {}, s$1 = [], a$1 = /acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i, h$1 = Array.isArray;
  function v$1(n2, l2) {
    for (var u2 in l2)
      n2[u2] = l2[u2];
    return n2;
  }
  function p$1(n2) {
    var l2 = n2.parentNode;
    l2 && l2.removeChild(n2);
  }
  function y$1(l2, u2, t2) {
    var i2, o2, r2, f2 = {};
    for (r2 in u2)
      "key" == r2 ? i2 = u2[r2] : "ref" == r2 ? o2 = u2[r2] : f2[r2] = u2[r2];
    if (arguments.length > 2 && (f2.children = arguments.length > 3 ? n.call(arguments, 2) : t2), "function" == typeof l2 && null != l2.defaultProps)
      for (r2 in l2.defaultProps)
        void 0 === f2[r2] && (f2[r2] = l2.defaultProps[r2]);
    return d$1(l2, f2, i2, o2, null);
  }
  function d$1(n2, t2, i2, o2, r2) {
    var f2 = { type: n2, props: t2, key: i2, ref: o2, __k: null, __: null, __b: 0, __e: null, __d: void 0, __c: null, __h: null, constructor: void 0, __v: null == r2 ? ++u$1 : r2 };
    return null == r2 && null != l$1.vnode && l$1.vnode(f2), f2;
  }
  function _$3() {
    return { current: null };
  }
  function k$2(n2) {
    return n2.children;
  }
  function b$1(n2, l2) {
    this.props = n2, this.context = l2;
  }
  function g$2(n2, l2) {
    if (null == l2)
      return n2.__ ? g$2(n2.__, n2.__.__k.indexOf(n2) + 1) : null;
    for (var u2; l2 < n2.__k.length; l2++)
      if (null != (u2 = n2.__k[l2]) && null != u2.__e)
        return u2.__e;
    return "function" == typeof n2.type ? g$2(n2) : null;
  }
  function m$1(n2) {
    var l2, u2;
    if (null != (n2 = n2.__) && null != n2.__c) {
      for (n2.__e = n2.__c.base = null, l2 = 0; l2 < n2.__k.length; l2++)
        if (null != (u2 = n2.__k[l2]) && null != u2.__e) {
          n2.__e = n2.__c.base = u2.__e;
          break;
        }
      return m$1(n2);
    }
  }
  function w$2(n2) {
    (!n2.__d && (n2.__d = true) && i$1.push(n2) && !x$2.__r++ || o$2 !== l$1.debounceRendering) && ((o$2 = l$1.debounceRendering) || r$1)(x$2);
  }
  function x$2() {
    var n2, l2, u2, t2, o2, r2, e2, c2, s2;
    for (i$1.sort(f$1); n2 = i$1.shift(); )
      n2.__d && (l2 = i$1.length, t2 = void 0, o2 = void 0, r2 = void 0, c2 = (e2 = (u2 = n2).__v).__e, (s2 = u2.__P) && (t2 = [], o2 = [], (r2 = v$1({}, e2)).__v = e2.__v + 1, L$1(s2, e2, r2, u2.__n, void 0 !== s2.ownerSVGElement, null != e2.__h ? [c2] : null, t2, null == c2 ? g$2(e2) : c2, e2.__h, o2), M$1(t2, e2, o2), e2.__e != c2 && m$1(e2)), i$1.length > l2 && i$1.sort(f$1));
    x$2.__r = 0;
  }
  function P$2(n2, l2, u2, t2, i2, o2, r2, f2, e2, a2, v2) {
    var p2, y2, _2, b2, g2, m2, w2, x2, P2, S2, H2 = 0, I2 = t2 && t2.__k || s$1, T2 = I2.length, j2 = T2, z2 = l2.length;
    for (u2.__k = [], p2 = 0; p2 < z2; p2++)
      null != (b2 = u2.__k[p2] = null == (b2 = l2[p2]) || "boolean" == typeof b2 || "function" == typeof b2 ? null : "string" == typeof b2 || "number" == typeof b2 || "bigint" == typeof b2 ? d$1(null, b2, null, null, b2) : h$1(b2) ? d$1(k$2, { children: b2 }, null, null, null) : b2.__b > 0 ? d$1(b2.type, b2.props, b2.key, b2.ref ? b2.ref : null, b2.__v) : b2) && (b2.__ = u2, b2.__b = u2.__b + 1, -1 === (x2 = A$2(b2, I2, w2 = p2 + H2, j2)) ? _2 = c$1 : (_2 = I2[x2] || c$1, I2[x2] = void 0, j2--), L$1(n2, b2, _2, i2, o2, r2, f2, e2, a2, v2), g2 = b2.__e, (y2 = b2.ref) && _2.ref != y2 && (_2.ref && O$1(_2.ref, null, b2), v2.push(y2, b2.__c || g2, b2)), null != g2 && (null == m2 && (m2 = g2), S2 = !(P2 = _2 === c$1 || null === _2.__v) && x2 === w2, P2 ? -1 == x2 && H2-- : x2 !== w2 && (x2 === w2 + 1 ? (H2++, S2 = true) : x2 > w2 ? j2 > z2 - w2 ? (H2 += x2 - w2, S2 = true) : H2-- : H2 = x2 < w2 && x2 == w2 - 1 ? x2 - w2 : 0), w2 = p2 + H2, S2 = S2 || x2 == p2 && !P2, "function" != typeof b2.type || x2 === w2 && _2.__k !== b2.__k ? "function" == typeof b2.type || S2 ? void 0 !== b2.__d ? (e2 = b2.__d, b2.__d = void 0) : e2 = g2.nextSibling : e2 = $$1(n2, g2, e2) : e2 = C$1(b2, e2, n2), "function" == typeof u2.type && (u2.__d = e2)));
    for (u2.__e = m2, p2 = T2; p2--; )
      null != I2[p2] && ("function" == typeof u2.type && null != I2[p2].__e && I2[p2].__e == u2.__d && (u2.__d = I2[p2].__e.nextSibling), q$2(I2[p2], I2[p2]));
  }
  function C$1(n2, l2, u2) {
    for (var t2, i2 = n2.__k, o2 = 0; i2 && o2 < i2.length; o2++)
      (t2 = i2[o2]) && (t2.__ = n2, l2 = "function" == typeof t2.type ? C$1(t2, l2, u2) : $$1(u2, t2.__e, l2));
    return l2;
  }
  function S(n2, l2) {
    return l2 = l2 || [], null == n2 || "boolean" == typeof n2 || (h$1(n2) ? n2.some(function(n3) {
      S(n3, l2);
    }) : l2.push(n2)), l2;
  }
  function $$1(n2, l2, u2) {
    return null == u2 || u2.parentNode !== n2 ? n2.insertBefore(l2, null) : l2 == u2 && null != l2.parentNode || n2.insertBefore(l2, u2), l2.nextSibling;
  }
  function A$2(n2, l2, u2, t2) {
    var i2 = n2.key, o2 = n2.type, r2 = u2 - 1, f2 = u2 + 1, e2 = l2[u2];
    if (null === e2 || e2 && i2 == e2.key && o2 === e2.type)
      return u2;
    if (t2 > (null != e2 ? 1 : 0))
      for (; r2 >= 0 || f2 < l2.length; ) {
        if (r2 >= 0) {
          if ((e2 = l2[r2]) && i2 == e2.key && o2 === e2.type)
            return r2;
          r2--;
        }
        if (f2 < l2.length) {
          if ((e2 = l2[f2]) && i2 == e2.key && o2 === e2.type)
            return f2;
          f2++;
        }
      }
    return -1;
  }
  function H$1(n2, l2, u2, t2, i2) {
    var o2;
    for (o2 in u2)
      "children" === o2 || "key" === o2 || o2 in l2 || T$2(n2, o2, null, u2[o2], t2);
    for (o2 in l2)
      i2 && "function" != typeof l2[o2] || "children" === o2 || "key" === o2 || "value" === o2 || "checked" === o2 || u2[o2] === l2[o2] || T$2(n2, o2, l2[o2], u2[o2], t2);
  }
  function I$1(n2, l2, u2) {
    "-" === l2[0] ? n2.setProperty(l2, null == u2 ? "" : u2) : n2[l2] = null == u2 ? "" : "number" != typeof u2 || a$1.test(l2) ? u2 : u2 + "px";
  }
  function T$2(n2, l2, u2, t2, i2) {
    var o2;
    n:
      if ("style" === l2)
        if ("string" == typeof u2)
          n2.style.cssText = u2;
        else {
          if ("string" == typeof t2 && (n2.style.cssText = t2 = ""), t2)
            for (l2 in t2)
              u2 && l2 in u2 || I$1(n2.style, l2, "");
          if (u2)
            for (l2 in u2)
              t2 && u2[l2] === t2[l2] || I$1(n2.style, l2, u2[l2]);
        }
      else if ("o" === l2[0] && "n" === l2[1])
        o2 = l2 !== (l2 = l2.replace(/Capture$/, "")), l2 = l2.toLowerCase() in n2 ? l2.toLowerCase().slice(2) : l2.slice(2), n2.l || (n2.l = {}), n2.l[l2 + o2] = u2, u2 ? t2 || n2.addEventListener(l2, o2 ? z$2 : j$2, o2) : n2.removeEventListener(l2, o2 ? z$2 : j$2, o2);
      else if ("dangerouslySetInnerHTML" !== l2) {
        if (i2)
          l2 = l2.replace(/xlink(H|:h)/, "h").replace(/sName$/, "s");
        else if ("width" !== l2 && "height" !== l2 && "href" !== l2 && "list" !== l2 && "form" !== l2 && "tabIndex" !== l2 && "download" !== l2 && "rowSpan" !== l2 && "colSpan" !== l2 && l2 in n2)
          try {
            n2[l2] = null == u2 ? "" : u2;
            break n;
          } catch (n3) {
          }
        "function" == typeof u2 || (null == u2 || false === u2 && "-" !== l2[4] ? n2.removeAttribute(l2) : n2.setAttribute(l2, u2));
      }
  }
  function j$2(n2) {
    return this.l[n2.type + false](l$1.event ? l$1.event(n2) : n2);
  }
  function z$2(n2) {
    return this.l[n2.type + true](l$1.event ? l$1.event(n2) : n2);
  }
  function L$1(n2, u2, t2, i2, o2, r2, f2, e2, c2, s2) {
    var a2, p2, y2, d2, _2, g2, m2, w2, x2, C2, S2, $2, A2, H2, I2, T2 = u2.type;
    if (void 0 !== u2.constructor)
      return null;
    null != t2.__h && (c2 = t2.__h, e2 = u2.__e = t2.__e, u2.__h = null, r2 = [e2]), (a2 = l$1.__b) && a2(u2);
    try {
      n:
        if ("function" == typeof T2) {
          if (w2 = u2.props, x2 = (a2 = T2.contextType) && i2[a2.__c], C2 = a2 ? x2 ? x2.props.value : a2.__ : i2, t2.__c ? m2 = (p2 = u2.__c = t2.__c).__ = p2.__E : ("prototype" in T2 && T2.prototype.render ? u2.__c = p2 = new T2(w2, C2) : (u2.__c = p2 = new b$1(w2, C2), p2.constructor = T2, p2.render = B$2), x2 && x2.sub(p2), p2.props = w2, p2.state || (p2.state = {}), p2.context = C2, p2.__n = i2, y2 = p2.__d = true, p2.__h = [], p2._sb = []), null == p2.__s && (p2.__s = p2.state), null != T2.getDerivedStateFromProps && (p2.__s == p2.state && (p2.__s = v$1({}, p2.__s)), v$1(p2.__s, T2.getDerivedStateFromProps(w2, p2.__s))), d2 = p2.props, _2 = p2.state, p2.__v = u2, y2)
            null == T2.getDerivedStateFromProps && null != p2.componentWillMount && p2.componentWillMount(), null != p2.componentDidMount && p2.__h.push(p2.componentDidMount);
          else {
            if (null == T2.getDerivedStateFromProps && w2 !== d2 && null != p2.componentWillReceiveProps && p2.componentWillReceiveProps(w2, C2), !p2.__e && (null != p2.shouldComponentUpdate && false === p2.shouldComponentUpdate(w2, p2.__s, C2) || u2.__v === t2.__v)) {
              for (u2.__v !== t2.__v && (p2.props = w2, p2.state = p2.__s, p2.__d = false), u2.__e = t2.__e, u2.__k = t2.__k, u2.__k.forEach(function(n3) {
                n3 && (n3.__ = u2);
              }), S2 = 0; S2 < p2._sb.length; S2++)
                p2.__h.push(p2._sb[S2]);
              p2._sb = [], p2.__h.length && f2.push(p2);
              break n;
            }
            null != p2.componentWillUpdate && p2.componentWillUpdate(w2, p2.__s, C2), null != p2.componentDidUpdate && p2.__h.push(function() {
              p2.componentDidUpdate(d2, _2, g2);
            });
          }
          if (p2.context = C2, p2.props = w2, p2.__P = n2, p2.__e = false, $2 = l$1.__r, A2 = 0, "prototype" in T2 && T2.prototype.render) {
            for (p2.state = p2.__s, p2.__d = false, $2 && $2(u2), a2 = p2.render(p2.props, p2.state, p2.context), H2 = 0; H2 < p2._sb.length; H2++)
              p2.__h.push(p2._sb[H2]);
            p2._sb = [];
          } else
            do {
              p2.__d = false, $2 && $2(u2), a2 = p2.render(p2.props, p2.state, p2.context), p2.state = p2.__s;
            } while (p2.__d && ++A2 < 25);
          p2.state = p2.__s, null != p2.getChildContext && (i2 = v$1(v$1({}, i2), p2.getChildContext())), y2 || null == p2.getSnapshotBeforeUpdate || (g2 = p2.getSnapshotBeforeUpdate(d2, _2)), P$2(n2, h$1(I2 = null != a2 && a2.type === k$2 && null == a2.key ? a2.props.children : a2) ? I2 : [I2], u2, t2, i2, o2, r2, f2, e2, c2, s2), p2.base = u2.__e, u2.__h = null, p2.__h.length && f2.push(p2), m2 && (p2.__E = p2.__ = null);
        } else
          null == r2 && u2.__v === t2.__v ? (u2.__k = t2.__k, u2.__e = t2.__e) : u2.__e = N$1(t2.__e, u2, t2, i2, o2, r2, f2, c2, s2);
      (a2 = l$1.diffed) && a2(u2);
    } catch (n3) {
      u2.__v = null, (c2 || null != r2) && (u2.__e = e2, u2.__h = !!c2, r2[r2.indexOf(e2)] = null), l$1.__e(n3, u2, t2);
    }
  }
  function M$1(n2, u2, t2) {
    for (var i2 = 0; i2 < t2.length; i2++)
      O$1(t2[i2], t2[++i2], t2[++i2]);
    l$1.__c && l$1.__c(u2, n2), n2.some(function(u3) {
      try {
        n2 = u3.__h, u3.__h = [], n2.some(function(n3) {
          n3.call(u3);
        });
      } catch (n3) {
        l$1.__e(n3, u3.__v);
      }
    });
  }
  function N$1(l2, u2, t2, i2, o2, r2, f2, e2, s2) {
    var a2, v2, y2, d2 = t2.props, _2 = u2.props, k2 = u2.type, b2 = 0;
    if ("svg" === k2 && (o2 = true), null != r2) {
      for (; b2 < r2.length; b2++)
        if ((a2 = r2[b2]) && "setAttribute" in a2 == !!k2 && (k2 ? a2.localName === k2 : 3 === a2.nodeType)) {
          l2 = a2, r2[b2] = null;
          break;
        }
    }
    if (null == l2) {
      if (null === k2)
        return document.createTextNode(_2);
      l2 = o2 ? document.createElementNS("http://www.w3.org/2000/svg", k2) : document.createElement(k2, _2.is && _2), r2 = null, e2 = false;
    }
    if (null === k2)
      d2 === _2 || e2 && l2.data === _2 || (l2.data = _2);
    else {
      if (r2 = r2 && n.call(l2.childNodes), v2 = (d2 = t2.props || c$1).dangerouslySetInnerHTML, y2 = _2.dangerouslySetInnerHTML, !e2) {
        if (null != r2)
          for (d2 = {}, b2 = 0; b2 < l2.attributes.length; b2++)
            d2[l2.attributes[b2].name] = l2.attributes[b2].value;
        (y2 || v2) && (y2 && (v2 && y2.__html == v2.__html || y2.__html === l2.innerHTML) || (l2.innerHTML = y2 && y2.__html || ""));
      }
      if (H$1(l2, _2, d2, o2, e2), y2)
        u2.__k = [];
      else if (P$2(l2, h$1(b2 = u2.props.children) ? b2 : [b2], u2, t2, i2, o2 && "foreignObject" !== k2, r2, f2, r2 ? r2[0] : t2.__k && g$2(t2, 0), e2, s2), null != r2)
        for (b2 = r2.length; b2--; )
          null != r2[b2] && p$1(r2[b2]);
      e2 || ("value" in _2 && void 0 !== (b2 = _2.value) && (b2 !== l2.value || "progress" === k2 && !b2 || "option" === k2 && b2 !== d2.value) && T$2(l2, "value", b2, d2.value, false), "checked" in _2 && void 0 !== (b2 = _2.checked) && b2 !== l2.checked && T$2(l2, "checked", b2, d2.checked, false));
    }
    return l2;
  }
  function O$1(n2, u2, t2) {
    try {
      "function" == typeof n2 ? n2(u2) : n2.current = u2;
    } catch (n3) {
      l$1.__e(n3, t2);
    }
  }
  function q$2(n2, u2, t2) {
    var i2, o2;
    if (l$1.unmount && l$1.unmount(n2), (i2 = n2.ref) && (i2.current && i2.current !== n2.__e || O$1(i2, null, u2)), null != (i2 = n2.__c)) {
      if (i2.componentWillUnmount)
        try {
          i2.componentWillUnmount();
        } catch (n3) {
          l$1.__e(n3, u2);
        }
      i2.base = i2.__P = null, n2.__c = void 0;
    }
    if (i2 = n2.__k)
      for (o2 = 0; o2 < i2.length; o2++)
        i2[o2] && q$2(i2[o2], u2, t2 || "function" != typeof n2.type);
    t2 || null == n2.__e || p$1(n2.__e), n2.__ = n2.__e = n2.__d = void 0;
  }
  function B$2(n2, l2, u2) {
    return this.constructor(n2, u2);
  }
  function D$1(u2, t2, i2) {
    var o2, r2, f2, e2;
    l$1.__ && l$1.__(u2, t2), r2 = (o2 = "function" == typeof i2) ? null : i2 && i2.__k || t2.__k, f2 = [], e2 = [], L$1(t2, u2 = (!o2 && i2 || t2).__k = y$1(k$2, null, [u2]), r2 || c$1, c$1, void 0 !== t2.ownerSVGElement, !o2 && i2 ? [i2] : r2 ? null : t2.firstChild ? n.call(t2.childNodes) : null, f2, !o2 && i2 ? i2 : r2 ? r2.__e : t2.firstChild, o2, e2), M$1(f2, u2, e2);
  }
  function E$1(n2, l2) {
    D$1(n2, l2, E$1);
  }
  function F$2(l2, u2, t2) {
    var i2, o2, r2, f2, e2 = v$1({}, l2.props);
    for (r2 in l2.type && l2.type.defaultProps && (f2 = l2.type.defaultProps), u2)
      "key" == r2 ? i2 = u2[r2] : "ref" == r2 ? o2 = u2[r2] : e2[r2] = void 0 === u2[r2] && void 0 !== f2 ? f2[r2] : u2[r2];
    return arguments.length > 2 && (e2.children = arguments.length > 3 ? n.call(arguments, 2) : t2), d$1(l2.type, e2, i2 || l2.key, o2 || l2.ref, null);
  }
  function G$1(n2, l2) {
    var u2 = { __c: l2 = "__cC" + e$1++, __: n2, Consumer: function(n3, l3) {
      return n3.children(l3);
    }, Provider: function(n3) {
      var u3, t2;
      return this.getChildContext || (u3 = [], (t2 = {})[l2] = this, this.getChildContext = function() {
        return t2;
      }, this.shouldComponentUpdate = function(n4) {
        this.props.value !== n4.value && u3.some(function(n5) {
          n5.__e = true, w$2(n5);
        });
      }, this.sub = function(n4) {
        u3.push(n4);
        var l3 = n4.componentWillUnmount;
        n4.componentWillUnmount = function() {
          u3.splice(u3.indexOf(n4), 1), l3 && l3.call(n4);
        };
      }), n3.children;
    } };
    return u2.Provider.__ = u2.Consumer.contextType = u2;
  }
  n = s$1.slice, l$1 = { __e: function(n2, l2, u2, t2) {
    for (var i2, o2, r2; l2 = l2.__; )
      if ((i2 = l2.__c) && !i2.__)
        try {
          if ((o2 = i2.constructor) && null != o2.getDerivedStateFromError && (i2.setState(o2.getDerivedStateFromError(n2)), r2 = i2.__d), null != i2.componentDidCatch && (i2.componentDidCatch(n2, t2 || {}), r2 = i2.__d), r2)
            return i2.__E = i2;
        } catch (l3) {
          n2 = l3;
        }
    throw n2;
  } }, u$1 = 0, b$1.prototype.setState = function(n2, l2) {
    var u2;
    u2 = null != this.__s && this.__s !== this.state ? this.__s : this.__s = v$1({}, this.state), "function" == typeof n2 && (n2 = n2(v$1({}, u2), this.props)), n2 && v$1(u2, n2), null != n2 && this.__v && (l2 && this._sb.push(l2), w$2(this));
  }, b$1.prototype.forceUpdate = function(n2) {
    this.__v && (this.__e = true, n2 && this.__h.push(n2), w$2(this));
  }, b$1.prototype.render = k$2, i$1 = [], r$1 = "function" == typeof Promise ? Promise.prototype.then.bind(Promise.resolve()) : setTimeout, f$1 = function(n2, l2) {
    return n2.__v.__b - l2.__v.__b;
  }, x$2.__r = 0, e$1 = 0;
  var t, r, u, i, o$1 = 0, f = [], c = [], e = l$1.__b, a = l$1.__r, v = l$1.diffed, l = l$1.__c, m = l$1.unmount;
  function d(t2, u2) {
    l$1.__h && l$1.__h(r, t2, o$1 || u2), o$1 = 0;
    var i2 = r.__H || (r.__H = { __: [], __h: [] });
    return t2 >= i2.__.length && i2.__.push({ __V: c }), i2.__[t2];
  }
  function h(n2) {
    return o$1 = 1, s(B$1, n2);
  }
  function s(n2, u2, i2) {
    var o2 = d(t++, 2);
    if (o2.t = n2, !o2.__c && (o2.__ = [i2 ? i2(u2) : B$1(void 0, u2), function(n3) {
      var t2 = o2.__N ? o2.__N[0] : o2.__[0], r2 = o2.t(t2, n3);
      t2 !== r2 && (o2.__N = [r2, o2.__[1]], o2.__c.setState({}));
    }], o2.__c = r, !r.u)) {
      var f2 = function(n3, t2, r2) {
        if (!o2.__c.__H)
          return true;
        var u3 = o2.__c.__H.__.filter(function(n4) {
          return n4.__c;
        });
        if (u3.every(function(n4) {
          return !n4.__N;
        }))
          return !c2 || c2.call(this, n3, t2, r2);
        var i3 = false;
        return u3.forEach(function(n4) {
          if (n4.__N) {
            var t3 = n4.__[0];
            n4.__ = n4.__N, n4.__N = void 0, t3 !== n4.__[0] && (i3 = true);
          }
        }), !(!i3 && o2.__c.props === n3) && (!c2 || c2.call(this, n3, t2, r2));
      };
      r.u = true;
      var c2 = r.shouldComponentUpdate, e2 = r.componentWillUpdate;
      r.componentWillUpdate = function(n3, t2, r2) {
        if (this.__e) {
          var u3 = c2;
          c2 = void 0, f2(n3, t2, r2), c2 = u3;
        }
        e2 && e2.call(this, n3, t2, r2);
      }, r.shouldComponentUpdate = f2;
    }
    return o2.__N || o2.__;
  }
  function p(u2, i2) {
    var o2 = d(t++, 3);
    !l$1.__s && z$1(o2.__H, i2) && (o2.__ = u2, o2.i = i2, r.__H.__h.push(o2));
  }
  function y(u2, i2) {
    var o2 = d(t++, 4);
    !l$1.__s && z$1(o2.__H, i2) && (o2.__ = u2, o2.i = i2, r.__h.push(o2));
  }
  function _$2(n2) {
    return o$1 = 5, F$1(function() {
      return { current: n2 };
    }, []);
  }
  function A$1(n2, t2, r2) {
    o$1 = 6, y(function() {
      return "function" == typeof n2 ? (n2(t2()), function() {
        return n2(null);
      }) : n2 ? (n2.current = t2(), function() {
        return n2.current = null;
      }) : void 0;
    }, null == r2 ? r2 : r2.concat(n2));
  }
  function F$1(n2, r2) {
    var u2 = d(t++, 7);
    return z$1(u2.__H, r2) ? (u2.__V = n2(), u2.i = r2, u2.__h = n2, u2.__V) : u2.__;
  }
  function T$1(n2, t2) {
    return o$1 = 8, F$1(function() {
      return n2;
    }, t2);
  }
  function q$1(n2) {
    var u2 = r.context[n2.__c], i2 = d(t++, 9);
    return i2.c = n2, u2 ? (null == i2.__ && (i2.__ = true, u2.sub(r)), u2.props.value) : n2.__;
  }
  function x$1(t2, r2) {
    l$1.useDebugValue && l$1.useDebugValue(r2 ? r2(t2) : t2);
  }
  function P$1(n2) {
    var u2 = d(t++, 10), i2 = h();
    return u2.__ = n2, r.componentDidCatch || (r.componentDidCatch = function(n3, t2) {
      u2.__ && u2.__(n3, t2), i2[1](n3);
    }), [i2[0], function() {
      i2[1](void 0);
    }];
  }
  function V$1() {
    var n2 = d(t++, 11);
    if (!n2.__) {
      for (var u2 = r.__v; null !== u2 && !u2.__m && null !== u2.__; )
        u2 = u2.__;
      var i2 = u2.__m || (u2.__m = [0, 0]);
      n2.__ = "P" + i2[0] + "-" + i2[1]++;
    }
    return n2.__;
  }
  function b() {
    for (var t2; t2 = f.shift(); )
      if (t2.__P && t2.__H)
        try {
          t2.__H.__h.forEach(k$1), t2.__H.__h.forEach(w$1), t2.__H.__h = [];
        } catch (r2) {
          t2.__H.__h = [], l$1.__e(r2, t2.__v);
        }
  }
  l$1.__b = function(n2) {
    r = null, e && e(n2);
  }, l$1.__r = function(n2) {
    a && a(n2), t = 0;
    var i2 = (r = n2.__c).__H;
    i2 && (u === r ? (i2.__h = [], r.__h = [], i2.__.forEach(function(n3) {
      n3.__N && (n3.__ = n3.__N), n3.__V = c, n3.__N = n3.i = void 0;
    })) : (i2.__h.forEach(k$1), i2.__h.forEach(w$1), i2.__h = [], t = 0)), u = r;
  }, l$1.diffed = function(t2) {
    v && v(t2);
    var o2 = t2.__c;
    o2 && o2.__H && (o2.__H.__h.length && (1 !== f.push(o2) && i === l$1.requestAnimationFrame || ((i = l$1.requestAnimationFrame) || j$1)(b)), o2.__H.__.forEach(function(n2) {
      n2.i && (n2.__H = n2.i), n2.__V !== c && (n2.__ = n2.__V), n2.i = void 0, n2.__V = c;
    })), u = r = null;
  }, l$1.__c = function(t2, r2) {
    r2.some(function(t3) {
      try {
        t3.__h.forEach(k$1), t3.__h = t3.__h.filter(function(n2) {
          return !n2.__ || w$1(n2);
        });
      } catch (u2) {
        r2.some(function(n2) {
          n2.__h && (n2.__h = []);
        }), r2 = [], l$1.__e(u2, t3.__v);
      }
    }), l && l(t2, r2);
  }, l$1.unmount = function(t2) {
    m && m(t2);
    var r2, u2 = t2.__c;
    u2 && u2.__H && (u2.__H.__.forEach(function(n2) {
      try {
        k$1(n2);
      } catch (n3) {
        r2 = n3;
      }
    }), u2.__H = void 0, r2 && l$1.__e(r2, u2.__v));
  };
  var g$1 = "function" == typeof requestAnimationFrame;
  function j$1(n2) {
    var t2, r2 = function() {
      clearTimeout(u2), g$1 && cancelAnimationFrame(t2), setTimeout(n2);
    }, u2 = setTimeout(r2, 100);
    g$1 && (t2 = requestAnimationFrame(r2));
  }
  function k$1(n2) {
    var t2 = r, u2 = n2.__c;
    "function" == typeof u2 && (n2.__c = void 0, u2()), r = t2;
  }
  function w$1(n2) {
    var t2 = r;
    n2.__c = n2.__(), r = t2;
  }
  function z$1(n2, t2) {
    return !n2 || n2.length !== t2.length || t2.some(function(t3, r2) {
      return t3 !== n2[r2];
    });
  }
  function B$1(n2, t2) {
    return "function" == typeof t2 ? t2(n2) : t2;
  }
  function synchronousWaitForElement(elementToWaitForSelector, timeout = 1e3) {
    let elementToWaitFor = document.querySelector(elementToWaitForSelector);
    const start = Date.now();
    while (!elementToWaitFor && Date.now() - start < timeout) {
      elementToWaitFor = document.querySelector(elementToWaitForSelector);
    }
    if (!elementToWaitFor) {
      throw new Error(`synchronousWaitForElement(): Element '${elementToWaitForSelector}' was not found`);
    }
    return elementToWaitFor;
  }
  function removeDuplicatedComponent(componentElementID) {
    const componentElement = document.getElementById(componentElementID);
    if (componentElement) {
      componentElement.remove();
    }
  }
  function g(n2, t2) {
    for (var e2 in t2)
      n2[e2] = t2[e2];
    return n2;
  }
  function C(n2, t2) {
    for (var e2 in n2)
      if ("__source" !== e2 && !(e2 in t2))
        return true;
    for (var r2 in t2)
      if ("__source" !== r2 && n2[r2] !== t2[r2])
        return true;
    return false;
  }
  function E(n2, t2) {
    return n2 === t2 && (0 !== n2 || 1 / n2 == 1 / t2) || n2 != n2 && t2 != t2;
  }
  function w(n2) {
    this.props = n2;
  }
  function x(n2, e2) {
    function r2(n3) {
      var t2 = this.props.ref, r3 = t2 == n3.ref;
      return !r3 && t2 && (t2.call ? t2(null) : t2.current = null), e2 ? !e2(this.props, n3) || !r3 : C(this.props, n3);
    }
    function u2(e3) {
      return this.shouldComponentUpdate = r2, y$1(n2, e3);
    }
    return u2.displayName = "Memo(" + (n2.displayName || n2.name) + ")", u2.prototype.isReactComponent = true, u2.__f = true, u2;
  }
  (w.prototype = new b$1()).isPureReactComponent = true, w.prototype.shouldComponentUpdate = function(n2, t2) {
    return C(this.props, n2) || C(this.state, t2);
  };
  var R = l$1.__b;
  l$1.__b = function(n2) {
    n2.type && n2.type.__f && n2.ref && (n2.props.ref = n2.ref, n2.ref = null), R && R(n2);
  };
  var N = "undefined" != typeof Symbol && Symbol.for && Symbol.for("react.forward_ref") || 3911;
  function k(n2) {
    function t2(t3) {
      var e2 = g({}, t3);
      return delete e2.ref, n2(e2, t3.ref || null);
    }
    return t2.$$typeof = N, t2.render = t2, t2.prototype.isReactComponent = t2.__f = true, t2.displayName = "ForwardRef(" + (n2.displayName || n2.name) + ")", t2;
  }
  var A = function(n2, t2) {
    return null == n2 ? null : S(S(n2).map(t2));
  }, O = { map: A, forEach: A, count: function(n2) {
    return n2 ? S(n2).length : 0;
  }, only: function(n2) {
    var t2 = S(n2);
    if (1 !== t2.length)
      throw "Children.only";
    return t2[0];
  }, toArray: S }, T = l$1.__e;
  l$1.__e = function(n2, t2, e2, r2) {
    if (n2.then) {
      for (var u2, o2 = t2; o2 = o2.__; )
        if ((u2 = o2.__c) && u2.__c)
          return null == t2.__e && (t2.__e = e2.__e, t2.__k = e2.__k), u2.__c(n2, t2);
    }
    T(n2, t2, e2, r2);
  };
  var I = l$1.unmount;
  function L(n2, t2, e2) {
    return n2 && (n2.__c && n2.__c.__H && (n2.__c.__H.__.forEach(function(n3) {
      "function" == typeof n3.__c && n3.__c();
    }), n2.__c.__H = null), null != (n2 = g({}, n2)).__c && (n2.__c.__P === e2 && (n2.__c.__P = t2), n2.__c = null), n2.__k = n2.__k && n2.__k.map(function(n3) {
      return L(n3, t2, e2);
    })), n2;
  }
  function U(n2, t2, e2) {
    return n2 && (n2.__v = null, n2.__k = n2.__k && n2.__k.map(function(n3) {
      return U(n3, t2, e2);
    }), n2.__c && n2.__c.__P === t2 && (n2.__e && e2.insertBefore(n2.__e, n2.__d), n2.__c.__e = true, n2.__c.__P = e2)), n2;
  }
  function D() {
    this.__u = 0, this.t = null, this.__b = null;
  }
  function F(n2) {
    var t2 = n2.__.__c;
    return t2 && t2.__a && t2.__a(n2);
  }
  function M(n2) {
    var e2, r2, u2;
    function o2(o3) {
      if (e2 || (e2 = n2()).then(function(n3) {
        r2 = n3.default || n3;
      }, function(n3) {
        u2 = n3;
      }), u2)
        throw u2;
      if (!r2)
        throw e2;
      return y$1(r2, o3);
    }
    return o2.displayName = "Lazy", o2.__f = true, o2;
  }
  function V() {
    this.u = null, this.o = null;
  }
  l$1.unmount = function(n2) {
    var t2 = n2.__c;
    t2 && t2.__R && t2.__R(), t2 && true === n2.__h && (n2.type = null), I && I(n2);
  }, (D.prototype = new b$1()).__c = function(n2, t2) {
    var e2 = t2.__c, r2 = this;
    null == r2.t && (r2.t = []), r2.t.push(e2);
    var u2 = F(r2.__v), o2 = false, i2 = function() {
      o2 || (o2 = true, e2.__R = null, u2 ? u2(l2) : l2());
    };
    e2.__R = i2;
    var l2 = function() {
      if (!--r2.__u) {
        if (r2.state.__a) {
          var n3 = r2.state.__a;
          r2.__v.__k[0] = U(n3, n3.__c.__P, n3.__c.__O);
        }
        var t3;
        for (r2.setState({ __a: r2.__b = null }); t3 = r2.t.pop(); )
          t3.forceUpdate();
      }
    }, c2 = true === t2.__h;
    r2.__u++ || c2 || r2.setState({ __a: r2.__b = r2.__v.__k[0] }), n2.then(i2, i2);
  }, D.prototype.componentWillUnmount = function() {
    this.t = [];
  }, D.prototype.render = function(n2, e2) {
    if (this.__b) {
      if (this.__v.__k) {
        var r2 = document.createElement("div"), o2 = this.__v.__k[0].__c;
        this.__v.__k[0] = L(this.__b, r2, o2.__O = o2.__P);
      }
      this.__b = null;
    }
    var i2 = e2.__a && y$1(k$2, null, n2.fallback);
    return i2 && (i2.__h = null), [y$1(k$2, null, e2.__a ? null : n2.children), i2];
  };
  var W = function(n2, t2, e2) {
    if (++e2[1] === e2[0] && n2.o.delete(t2), n2.props.revealOrder && ("t" !== n2.props.revealOrder[0] || !n2.o.size))
      for (e2 = n2.u; e2; ) {
        for (; e2.length > 3; )
          e2.pop()();
        if (e2[1] < e2[0])
          break;
        n2.u = e2 = e2[2];
      }
  };
  function P(n2) {
    return this.getChildContext = function() {
      return n2.context;
    }, n2.children;
  }
  function j(n2) {
    var e2 = this, r2 = n2.i;
    e2.componentWillUnmount = function() {
      D$1(null, e2.l), e2.l = null, e2.i = null;
    }, e2.i && e2.i !== r2 && e2.componentWillUnmount(), n2.__v ? (e2.l || (e2.i = r2, e2.l = { nodeType: 1, parentNode: r2, childNodes: [], appendChild: function(n3) {
      this.childNodes.push(n3), e2.i.appendChild(n3);
    }, insertBefore: function(n3, t2) {
      this.childNodes.push(n3), e2.i.appendChild(n3);
    }, removeChild: function(n3) {
      this.childNodes.splice(this.childNodes.indexOf(n3) >>> 1, 1), e2.i.removeChild(n3);
    } }), D$1(y$1(P, { context: e2.context }, n2.__v), e2.l)) : e2.l && e2.componentWillUnmount();
  }
  function z(n2, e2) {
    var r2 = y$1(j, { __v: n2, i: e2 });
    return r2.containerInfo = e2, r2;
  }
  (V.prototype = new b$1()).__a = function(n2) {
    var t2 = this, e2 = F(t2.__v), r2 = t2.o.get(n2);
    return r2[0]++, function(u2) {
      var o2 = function() {
        t2.props.revealOrder ? (r2.push(u2), W(t2, n2, r2)) : u2();
      };
      e2 ? e2(o2) : o2();
    };
  }, V.prototype.render = function(n2) {
    this.u = null, this.o = /* @__PURE__ */ new Map();
    var t2 = S(n2.children);
    n2.revealOrder && "b" === n2.revealOrder[0] && t2.reverse();
    for (var e2 = t2.length; e2--; )
      this.o.set(t2[e2], this.u = [1, 0, this.u]);
    return n2.children;
  }, V.prototype.componentDidUpdate = V.prototype.componentDidMount = function() {
    var n2 = this;
    this.o.forEach(function(t2, e2) {
      W(n2, e2, t2);
    });
  };
  var B = "undefined" != typeof Symbol && Symbol.for && Symbol.for("react.element") || 60103, H = /^(?:accent|alignment|arabic|baseline|cap|clip(?!PathU)|color|dominant|fill|flood|font|glyph(?!R)|horiz|image(!S)|letter|lighting|marker(?!H|W|U)|overline|paint|pointer|shape|stop|strikethrough|stroke|text(?!L)|transform|underline|unicode|units|v|vector|vert|word|writing|x(?!C))[A-Z]/, Z = /^on(Ani|Tra|Tou|BeforeInp|Compo)/, Y = /[A-Z0-9]/g, $ = "undefined" != typeof document, q = function(n2) {
    return ("undefined" != typeof Symbol && "symbol" == typeof Symbol() ? /fil|che|rad/ : /fil|che|ra/).test(n2);
  };
  function G(n2, t2, e2) {
    return null == t2.__k && (t2.textContent = ""), D$1(n2, t2), "function" == typeof e2 && e2(), n2 ? n2.__c : null;
  }
  function J(n2, t2, e2) {
    return E$1(n2, t2), "function" == typeof e2 && e2(), n2 ? n2.__c : null;
  }
  b$1.prototype.isReactComponent = {}, ["componentWillMount", "componentWillReceiveProps", "componentWillUpdate"].forEach(function(t2) {
    Object.defineProperty(b$1.prototype, t2, { configurable: true, get: function() {
      return this["UNSAFE_" + t2];
    }, set: function(n2) {
      Object.defineProperty(this, t2, { configurable: true, writable: true, value: n2 });
    } });
  });
  var K = l$1.event;
  function Q() {
  }
  function X() {
    return this.cancelBubble;
  }
  function nn() {
    return this.defaultPrevented;
  }
  l$1.event = function(n2) {
    return K && (n2 = K(n2)), n2.persist = Q, n2.isPropagationStopped = X, n2.isDefaultPrevented = nn, n2.nativeEvent = n2;
  };
  var tn, en = { enumerable: false, configurable: true, get: function() {
    return this.class;
  } }, rn = l$1.vnode;
  l$1.vnode = function(n2) {
    "string" == typeof n2.type && function(n3) {
      var t2 = n3.props, e2 = n3.type, u2 = {};
      for (var o2 in t2) {
        var i2 = t2[o2];
        if (!("value" === o2 && "defaultValue" in t2 && null == i2 || $ && "children" === o2 && "noscript" === e2 || "class" === o2 || "className" === o2)) {
          var l2 = o2.toLowerCase();
          "defaultValue" === o2 && "value" in t2 && null == t2.value ? o2 = "value" : "download" === o2 && true === i2 ? i2 = "" : "ondoubleclick" === l2 ? o2 = "ondblclick" : "onchange" !== l2 || "input" !== e2 && "textarea" !== e2 || q(t2.type) ? "onfocus" === l2 ? o2 = "onfocusin" : "onblur" === l2 ? o2 = "onfocusout" : Z.test(o2) ? o2 = l2 : -1 === e2.indexOf("-") && H.test(o2) ? o2 = o2.replace(Y, "-$&").toLowerCase() : null === i2 && (i2 = void 0) : l2 = o2 = "oninput", "oninput" === l2 && u2[o2 = l2] && (o2 = "oninputCapture"), u2[o2] = i2;
        }
      }
      "select" == e2 && u2.multiple && Array.isArray(u2.value) && (u2.value = S(t2.children).forEach(function(n4) {
        n4.props.selected = -1 != u2.value.indexOf(n4.props.value);
      })), "select" == e2 && null != u2.defaultValue && (u2.value = S(t2.children).forEach(function(n4) {
        n4.props.selected = u2.multiple ? -1 != u2.defaultValue.indexOf(n4.props.value) : u2.defaultValue == n4.props.value;
      })), t2.class && !t2.className ? (u2.class = t2.class, Object.defineProperty(u2, "className", en)) : (t2.className && !t2.class || t2.class && t2.className) && (u2.class = u2.className = t2.className), n3.props = u2;
    }(n2), n2.$$typeof = B, rn && rn(n2);
  };
  var un = l$1.__r;
  l$1.__r = function(n2) {
    un && un(n2), tn = n2.__c;
  };
  var on = l$1.diffed;
  l$1.diffed = function(n2) {
    on && on(n2);
    var t2 = n2.props, e2 = n2.__e;
    null != e2 && "textarea" === n2.type && "value" in t2 && t2.value !== e2.value && (e2.value = null == t2.value ? "" : t2.value), tn = null;
  };
  var ln = { ReactCurrentDispatcher: { current: { readContext: function(n2) {
    return tn.__n[n2.__c].props.value;
  } } } }, cn = "17.0.2";
  function fn(n2) {
    return y$1.bind(null, n2);
  }
  function an(n2) {
    return !!n2 && n2.$$typeof === B;
  }
  function sn(n2) {
    return an(n2) ? F$2.apply(null, arguments) : n2;
  }
  function hn(n2) {
    return !!n2.__k && (D$1(null, n2), true);
  }
  function vn(n2) {
    return n2 && (n2.base || 1 === n2.nodeType && n2) || null;
  }
  var dn = function(n2, t2) {
    return n2(t2);
  }, pn = function(n2, t2) {
    return n2(t2);
  }, mn = k$2;
  function yn(n2) {
    n2();
  }
  function _n(n2) {
    return n2;
  }
  function bn() {
    return [false, yn];
  }
  var Sn = y;
  function gn(n2, t2) {
    var e2 = t2(), r2 = h({ h: { __: e2, v: t2 } }), u2 = r2[0].h, o2 = r2[1];
    return y(function() {
      u2.__ = e2, u2.v = t2, E(u2.__, t2()) || o2({ h: u2 });
    }, [n2, e2, t2]), p(function() {
      return E(u2.__, u2.v()) || o2({ h: u2 }), n2(function() {
        E(u2.__, u2.v()) || o2({ h: u2 });
      });
    }, [n2]), e2;
  }
  var Cn = { useState: h, useId: V$1, useReducer: s, useEffect: p, useLayoutEffect: y, useInsertionEffect: Sn, useTransition: bn, useDeferredValue: _n, useSyncExternalStore: gn, startTransition: yn, useRef: _$2, useImperativeHandle: A$1, useMemo: F$1, useCallback: T$1, useContext: q$1, useDebugValue: x$1, version: "17.0.2", Children: O, render: G, hydrate: J, unmountComponentAtNode: hn, createPortal: z, createElement: y$1, createContext: G$1, createFactory: fn, cloneElement: sn, createRef: _$3, Fragment: k$2, isValidElement: an, findDOMNode: vn, Component: b$1, PureComponent: w, memo: x, forwardRef: k, flushSync: pn, unstable_batchedUpdates: dn, StrictMode: mn, Suspense: D, SuspenseList: V, lazy: M, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ln };
  const $2AODx$react = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    Children: O,
    Component: b$1,
    Fragment: k$2,
    PureComponent: w,
    StrictMode: mn,
    Suspense: D,
    SuspenseList: V,
    __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: ln,
    cloneElement: sn,
    createContext: G$1,
    createElement: y$1,
    createFactory: fn,
    createPortal: z,
    createRef: _$3,
    default: Cn,
    findDOMNode: vn,
    flushSync: pn,
    forwardRef: k,
    hydrate: J,
    isValidElement: an,
    lazy: M,
    memo: x,
    render: G,
    startTransition: yn,
    unmountComponentAtNode: hn,
    unstable_batchedUpdates: dn,
    useCallback: T$1,
    useContext: q$1,
    useDebugValue: x$1,
    useDeferredValue: _n,
    useEffect: p,
    useErrorBoundary: P$1,
    useId: V$1,
    useImperativeHandle: A$1,
    useInsertionEffect: Sn,
    useLayoutEffect: y,
    useMemo: F$1,
    useReducer: s,
    useRef: _$2,
    useState: h,
    useSyncExternalStore: gn,
    useTransition: bn,
    version: cn
  }, Symbol.toStringTag, { value: "Module" }));
  const placeHolderValue$4 = {
    open: false,
    options: {
      title: "AlertContext placeholder title",
      text: "AlertContext placeholder text",
      okButtonText: "AlertContext placeholder OK",
      cancelButtonText: "AlertContext placeholder CANCEL",
      okCallback: () => {
        console.log("AlertContext.options.okCallback() placeholder function executed. This should be replaced by a new function.");
      },
      cancelCallback: () => {
        console.log("AlertContext.options.okCallback() placeholder function executed. This should be replaced by a new function.");
      }
    },
    setOpen: () => {
      console.log("AlertContext.setOpen() placeholder function executed. This should be replaced by a new function.");
    },
    setClosed: () => {
      console.log("AlertContext.setClosed() placeholder function executed. This should be replaced by a new function.");
    },
    setOptions: ({
      title: title2,
      text
    }) => {
      console.log("AlertContext.setOptions() placeholder function executed. This should be replaced by a new function.");
      console.log(` - language: ${title2}`);
      console.log(` - enableCustomSelection: ${text}`);
    }
  };
  const AlertContext = G$1(placeHolderValue$4);
  const placeHolderValue$3 = {
    dialogueOpen: false,
    uniqueId: null,
    config: null,
    app: null,
    db: null,
    syncedStatistics: {},
    syncedSettings: {},
    syncedExercisesStorage: [],
    syncedSelectionsStorage: [],
    openDialogue: () => {
      console.log("FirebaseContext.openDialogue() placeholder function executed. This should be replaced by a new function.");
    },
    closeDialogue: () => {
      console.log("FirebaseContext.closeDialogue() placeholder function executed. This should be replaced by a new function.");
    },
    initiateUniqueId: () => {
      console.log("FirebaseContext.initiateUniqueId() placeholder function executed. This should be replaced by a new function.");
      return new Promise((r2) => {
        r2();
      });
    },
    setConfig: (config) => {
      console.log("FirebaseContext.setConfig() placeholder function executed. This should be replaced by a new function.");
      console.log(` - config: ${config}`);
    }
  };
  const FirebaseContext = G$1(placeHolderValue$3);
  var NotificationType = /* @__PURE__ */ ((NotificationType2) => {
    NotificationType2[NotificationType2["NOTIFICATION"] = 0] = "NOTIFICATION";
    NotificationType2[NotificationType2["WARNING"] = 1] = "WARNING";
    NotificationType2[NotificationType2["ERROR"] = 2] = "ERROR";
    return NotificationType2;
  })(NotificationType || {});
  const placeHolderValue$2 = {
    options: {
      title: "NotificationContext placeholder title",
      text: "NotificationContext placeholder text",
      type: 0,
      timeout: 5e3,
      showClose: false
    },
    setOptions: ({
      title: title2,
      text,
      type,
      timeout,
      showClose
    }) => {
      console.log(`NotificationContext placeholder function executed. This should be replaced by a new function.`);
      console.log(` - title: ${title2}`);
      console.log(` - text: ${text}`);
      console.log(` - type: ${type}`);
      console.log(` - timeout: ${timeout}`);
      console.log(` - showClose: ${showClose}`);
    }
  };
  const NotificationContext = G$1(placeHolderValue$2);
  const consoleLogger = {
    type: "logger",
    log(args) {
      this.output("log", args);
    },
    warn(args) {
      this.output("warn", args);
    },
    error(args) {
      this.output("error", args);
    },
    output(type, args) {
      if (console && console[type])
        console[type].apply(console, args);
    }
  };
  let Logger$1 = class Logger {
    constructor(concreteLogger) {
      let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      this.init(concreteLogger, options);
    }
    init(concreteLogger) {
      let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      this.prefix = options.prefix || "i18next:";
      this.logger = concreteLogger || consoleLogger;
      this.options = options;
      this.debug = options.debug;
    }
    log() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      return this.forward(args, "log", "", true);
    }
    warn() {
      for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
        args[_key2] = arguments[_key2];
      }
      return this.forward(args, "warn", "", true);
    }
    error() {
      for (var _len3 = arguments.length, args = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
        args[_key3] = arguments[_key3];
      }
      return this.forward(args, "error", "");
    }
    deprecate() {
      for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
        args[_key4] = arguments[_key4];
      }
      return this.forward(args, "warn", "WARNING DEPRECATED: ", true);
    }
    forward(args, lvl, prefix, debugOnly) {
      if (debugOnly && !this.debug)
        return null;
      if (typeof args[0] === "string")
        args[0] = `${prefix}${this.prefix} ${args[0]}`;
      return this.logger[lvl](args);
    }
    create(moduleName) {
      return new Logger(this.logger, {
        ...{
          prefix: `${this.prefix}:${moduleName}:`
        },
        ...this.options
      });
    }
    clone(options) {
      options = options || this.options;
      options.prefix = options.prefix || this.prefix;
      return new Logger(this.logger, options);
    }
  };
  var baseLogger = new Logger$1();
  let EventEmitter$1 = class EventEmitter {
    constructor() {
      this.observers = {};
    }
    on(events2, listener) {
      events2.split(" ").forEach((event) => {
        this.observers[event] = this.observers[event] || [];
        this.observers[event].push(listener);
      });
      return this;
    }
    off(event, listener) {
      if (!this.observers[event])
        return;
      if (!listener) {
        delete this.observers[event];
        return;
      }
      this.observers[event] = this.observers[event].filter((l2) => l2 !== listener);
    }
    emit(event) {
      for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        args[_key - 1] = arguments[_key];
      }
      if (this.observers[event]) {
        const cloned = [].concat(this.observers[event]);
        cloned.forEach((observer) => {
          observer(...args);
        });
      }
      if (this.observers["*"]) {
        const cloned = [].concat(this.observers["*"]);
        cloned.forEach((observer) => {
          observer.apply(observer, [event, ...args]);
        });
      }
    }
  };
  function defer() {
    let res;
    let rej;
    const promise = new Promise((resolve, reject) => {
      res = resolve;
      rej = reject;
    });
    promise.resolve = res;
    promise.reject = rej;
    return promise;
  }
  function makeString(object) {
    if (object == null)
      return "";
    return "" + object;
  }
  function copy(a2, s2, t2) {
    a2.forEach((m2) => {
      if (s2[m2])
        t2[m2] = s2[m2];
    });
  }
  function getLastOfPath(object, path, Empty) {
    function cleanKey(key) {
      return key && key.indexOf("###") > -1 ? key.replace(/###/g, ".") : key;
    }
    function canNotTraverseDeeper() {
      return !object || typeof object === "string";
    }
    const stack = typeof path !== "string" ? [].concat(path) : path.split(".");
    while (stack.length > 1) {
      if (canNotTraverseDeeper())
        return {};
      const key = cleanKey(stack.shift());
      if (!object[key] && Empty)
        object[key] = new Empty();
      if (Object.prototype.hasOwnProperty.call(object, key)) {
        object = object[key];
      } else {
        object = {};
      }
    }
    if (canNotTraverseDeeper())
      return {};
    return {
      obj: object,
      k: cleanKey(stack.shift())
    };
  }
  function setPath(object, path, newValue) {
    const {
      obj,
      k: k2
    } = getLastOfPath(object, path, Object);
    obj[k2] = newValue;
  }
  function pushPath(object, path, newValue, concat) {
    const {
      obj,
      k: k2
    } = getLastOfPath(object, path, Object);
    obj[k2] = obj[k2] || [];
    if (concat)
      obj[k2] = obj[k2].concat(newValue);
    if (!concat)
      obj[k2].push(newValue);
  }
  function getPath(object, path) {
    const {
      obj,
      k: k2
    } = getLastOfPath(object, path);
    if (!obj)
      return void 0;
    return obj[k2];
  }
  function getPathWithDefaults(data, defaultData2, key) {
    const value = getPath(data, key);
    if (value !== void 0) {
      return value;
    }
    return getPath(defaultData2, key);
  }
  function deepExtend$1(target, source, overwrite) {
    for (const prop in source) {
      if (prop !== "__proto__" && prop !== "constructor") {
        if (prop in target) {
          if (typeof target[prop] === "string" || target[prop] instanceof String || typeof source[prop] === "string" || source[prop] instanceof String) {
            if (overwrite)
              target[prop] = source[prop];
          } else {
            deepExtend$1(target[prop], source[prop], overwrite);
          }
        } else {
          target[prop] = source[prop];
        }
      }
    }
    return target;
  }
  function regexEscape(str) {
    return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  }
  var _entityMap = {
    "&": "&amp;",
    "<": "&lt;",
    ">": "&gt;",
    '"': "&quot;",
    "'": "&#39;",
    "/": "&#x2F;"
  };
  function escape$1(data) {
    if (typeof data === "string") {
      return data.replace(/[&<>"'\/]/g, (s2) => _entityMap[s2]);
    }
    return data;
  }
  const chars = [" ", ",", "?", "!", ";"];
  function looksLikeObjectPath(key, nsSeparator, keySeparator) {
    nsSeparator = nsSeparator || "";
    keySeparator = keySeparator || "";
    const possibleChars = chars.filter((c2) => nsSeparator.indexOf(c2) < 0 && keySeparator.indexOf(c2) < 0);
    if (possibleChars.length === 0)
      return true;
    const r2 = new RegExp(`(${possibleChars.map((c2) => c2 === "?" ? "\\?" : c2).join("|")})`);
    let matched = !r2.test(key);
    if (!matched) {
      const ki = key.indexOf(keySeparator);
      if (ki > 0 && !r2.test(key.substring(0, ki))) {
        matched = true;
      }
    }
    return matched;
  }
  function deepFind(obj, path) {
    let keySeparator = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : ".";
    if (!obj)
      return void 0;
    if (obj[path])
      return obj[path];
    const paths = path.split(keySeparator);
    let current = obj;
    for (let i2 = 0; i2 < paths.length; ++i2) {
      if (!current)
        return void 0;
      if (typeof current[paths[i2]] === "string" && i2 + 1 < paths.length) {
        return void 0;
      }
      if (current[paths[i2]] === void 0) {
        let j2 = 2;
        let p2 = paths.slice(i2, i2 + j2).join(keySeparator);
        let mix = current[p2];
        while (mix === void 0 && paths.length > i2 + j2) {
          j2++;
          p2 = paths.slice(i2, i2 + j2).join(keySeparator);
          mix = current[p2];
        }
        if (mix === void 0)
          return void 0;
        if (mix === null)
          return null;
        if (path.endsWith(p2)) {
          if (typeof mix === "string")
            return mix;
          if (p2 && typeof mix[p2] === "string")
            return mix[p2];
        }
        const joinedPath = paths.slice(i2 + j2).join(keySeparator);
        if (joinedPath)
          return deepFind(mix, joinedPath, keySeparator);
        return void 0;
      }
      current = current[paths[i2]];
    }
    return current;
  }
  function getCleanedCode(code) {
    if (code && code.indexOf("_") > 0)
      return code.replace("_", "-");
    return code;
  }
  class ResourceStore extends EventEmitter$1 {
    constructor(data) {
      let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
        ns: ["translation"],
        defaultNS: "translation"
      };
      super();
      this.data = data || {};
      this.options = options;
      if (this.options.keySeparator === void 0) {
        this.options.keySeparator = ".";
      }
      if (this.options.ignoreJSONStructure === void 0) {
        this.options.ignoreJSONStructure = true;
      }
    }
    addNamespaces(ns) {
      if (this.options.ns.indexOf(ns) < 0) {
        this.options.ns.push(ns);
      }
    }
    removeNamespaces(ns) {
      const index2 = this.options.ns.indexOf(ns);
      if (index2 > -1) {
        this.options.ns.splice(index2, 1);
      }
    }
    getResource(lng, ns, key) {
      let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
      const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
      const ignoreJSONStructure = options.ignoreJSONStructure !== void 0 ? options.ignoreJSONStructure : this.options.ignoreJSONStructure;
      let path = [lng, ns];
      if (key && typeof key !== "string")
        path = path.concat(key);
      if (key && typeof key === "string")
        path = path.concat(keySeparator ? key.split(keySeparator) : key);
      if (lng.indexOf(".") > -1) {
        path = lng.split(".");
      }
      const result = getPath(this.data, path);
      if (result || !ignoreJSONStructure || typeof key !== "string")
        return result;
      return deepFind(this.data && this.data[lng] && this.data[lng][ns], key, keySeparator);
    }
    addResource(lng, ns, key, value) {
      let options = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : {
        silent: false
      };
      const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
      let path = [lng, ns];
      if (key)
        path = path.concat(keySeparator ? key.split(keySeparator) : key);
      if (lng.indexOf(".") > -1) {
        path = lng.split(".");
        value = ns;
        ns = path[1];
      }
      this.addNamespaces(ns);
      setPath(this.data, path, value);
      if (!options.silent)
        this.emit("added", lng, ns, key, value);
    }
    addResources(lng, ns, resources2) {
      let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {
        silent: false
      };
      for (const m2 in resources2) {
        if (typeof resources2[m2] === "string" || Object.prototype.toString.apply(resources2[m2]) === "[object Array]")
          this.addResource(lng, ns, m2, resources2[m2], {
            silent: true
          });
      }
      if (!options.silent)
        this.emit("added", lng, ns, resources2);
    }
    addResourceBundle(lng, ns, resources2, deep, overwrite) {
      let options = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : {
        silent: false
      };
      let path = [lng, ns];
      if (lng.indexOf(".") > -1) {
        path = lng.split(".");
        deep = resources2;
        resources2 = ns;
        ns = path[1];
      }
      this.addNamespaces(ns);
      let pack = getPath(this.data, path) || {};
      if (deep) {
        deepExtend$1(pack, resources2, overwrite);
      } else {
        pack = {
          ...pack,
          ...resources2
        };
      }
      setPath(this.data, path, pack);
      if (!options.silent)
        this.emit("added", lng, ns, resources2);
    }
    removeResourceBundle(lng, ns) {
      if (this.hasResourceBundle(lng, ns)) {
        delete this.data[lng][ns];
      }
      this.removeNamespaces(ns);
      this.emit("removed", lng, ns);
    }
    hasResourceBundle(lng, ns) {
      return this.getResource(lng, ns) !== void 0;
    }
    getResourceBundle(lng, ns) {
      if (!ns)
        ns = this.options.defaultNS;
      if (this.options.compatibilityAPI === "v1")
        return {
          ...{},
          ...this.getResource(lng, ns)
        };
      return this.getResource(lng, ns);
    }
    getDataByLanguage(lng) {
      return this.data[lng];
    }
    hasLanguageSomeTranslations(lng) {
      const data = this.getDataByLanguage(lng);
      const n2 = data && Object.keys(data) || [];
      return !!n2.find((v2) => data[v2] && Object.keys(data[v2]).length > 0);
    }
    toJSON() {
      return this.data;
    }
  }
  var postProcessor = {
    processors: {},
    addPostProcessor(module) {
      this.processors[module.name] = module;
    },
    handle(processors, value, key, options, translator) {
      processors.forEach((processor) => {
        if (this.processors[processor])
          value = this.processors[processor].process(value, key, options, translator);
      });
      return value;
    }
  };
  const checkedLoadedFor = {};
  class Translator extends EventEmitter$1 {
    constructor(services) {
      let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      super();
      copy(["resourceStore", "languageUtils", "pluralResolver", "interpolator", "backendConnector", "i18nFormat", "utils"], services, this);
      this.options = options;
      if (this.options.keySeparator === void 0) {
        this.options.keySeparator = ".";
      }
      this.logger = baseLogger.create("translator");
    }
    changeLanguage(lng) {
      if (lng)
        this.language = lng;
    }
    exists(key) {
      let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
        interpolation: {}
      };
      if (key === void 0 || key === null) {
        return false;
      }
      const resolved = this.resolve(key, options);
      return resolved && resolved.res !== void 0;
    }
    extractFromKey(key, options) {
      let nsSeparator = options.nsSeparator !== void 0 ? options.nsSeparator : this.options.nsSeparator;
      if (nsSeparator === void 0)
        nsSeparator = ":";
      const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
      let namespaces = options.ns || this.options.defaultNS || [];
      const wouldCheckForNsInKey = nsSeparator && key.indexOf(nsSeparator) > -1;
      const seemsNaturalLanguage = !this.options.userDefinedKeySeparator && !options.keySeparator && !this.options.userDefinedNsSeparator && !options.nsSeparator && !looksLikeObjectPath(key, nsSeparator, keySeparator);
      if (wouldCheckForNsInKey && !seemsNaturalLanguage) {
        const m2 = key.match(this.interpolator.nestingRegexp);
        if (m2 && m2.length > 0) {
          return {
            key,
            namespaces
          };
        }
        const parts = key.split(nsSeparator);
        if (nsSeparator !== keySeparator || nsSeparator === keySeparator && this.options.ns.indexOf(parts[0]) > -1)
          namespaces = parts.shift();
        key = parts.join(keySeparator);
      }
      if (typeof namespaces === "string")
        namespaces = [namespaces];
      return {
        key,
        namespaces
      };
    }
    translate(keys, options, lastKey) {
      if (typeof options !== "object" && this.options.overloadTranslationOptionHandler) {
        options = this.options.overloadTranslationOptionHandler(arguments);
      }
      if (typeof options === "object")
        options = {
          ...options
        };
      if (!options)
        options = {};
      if (keys === void 0 || keys === null)
        return "";
      if (!Array.isArray(keys))
        keys = [String(keys)];
      const returnDetails = options.returnDetails !== void 0 ? options.returnDetails : this.options.returnDetails;
      const keySeparator = options.keySeparator !== void 0 ? options.keySeparator : this.options.keySeparator;
      const {
        key,
        namespaces
      } = this.extractFromKey(keys[keys.length - 1], options);
      const namespace = namespaces[namespaces.length - 1];
      const lng = options.lng || this.language;
      const appendNamespaceToCIMode = options.appendNamespaceToCIMode || this.options.appendNamespaceToCIMode;
      if (lng && lng.toLowerCase() === "cimode") {
        if (appendNamespaceToCIMode) {
          const nsSeparator = options.nsSeparator || this.options.nsSeparator;
          if (returnDetails) {
            return {
              res: `${namespace}${nsSeparator}${key}`,
              usedKey: key,
              exactUsedKey: key,
              usedLng: lng,
              usedNS: namespace
            };
          }
          return `${namespace}${nsSeparator}${key}`;
        }
        if (returnDetails) {
          return {
            res: key,
            usedKey: key,
            exactUsedKey: key,
            usedLng: lng,
            usedNS: namespace
          };
        }
        return key;
      }
      const resolved = this.resolve(keys, options);
      let res = resolved && resolved.res;
      const resUsedKey = resolved && resolved.usedKey || key;
      const resExactUsedKey = resolved && resolved.exactUsedKey || key;
      const resType = Object.prototype.toString.apply(res);
      const noObject = ["[object Number]", "[object Function]", "[object RegExp]"];
      const joinArrays = options.joinArrays !== void 0 ? options.joinArrays : this.options.joinArrays;
      const handleAsObjectInI18nFormat = !this.i18nFormat || this.i18nFormat.handleAsObject;
      const handleAsObject = typeof res !== "string" && typeof res !== "boolean" && typeof res !== "number";
      if (handleAsObjectInI18nFormat && res && handleAsObject && noObject.indexOf(resType) < 0 && !(typeof joinArrays === "string" && resType === "[object Array]")) {
        if (!options.returnObjects && !this.options.returnObjects) {
          if (!this.options.returnedObjectHandler) {
            this.logger.warn("accessing an object - but returnObjects options is not enabled!");
          }
          const r2 = this.options.returnedObjectHandler ? this.options.returnedObjectHandler(resUsedKey, res, {
            ...options,
            ns: namespaces
          }) : `key '${key} (${this.language})' returned an object instead of string.`;
          if (returnDetails) {
            resolved.res = r2;
            return resolved;
          }
          return r2;
        }
        if (keySeparator) {
          const resTypeIsArray = resType === "[object Array]";
          const copy2 = resTypeIsArray ? [] : {};
          const newKeyToUse = resTypeIsArray ? resExactUsedKey : resUsedKey;
          for (const m2 in res) {
            if (Object.prototype.hasOwnProperty.call(res, m2)) {
              const deepKey = `${newKeyToUse}${keySeparator}${m2}`;
              copy2[m2] = this.translate(deepKey, {
                ...options,
                ...{
                  joinArrays: false,
                  ns: namespaces
                }
              });
              if (copy2[m2] === deepKey)
                copy2[m2] = res[m2];
            }
          }
          res = copy2;
        }
      } else if (handleAsObjectInI18nFormat && typeof joinArrays === "string" && resType === "[object Array]") {
        res = res.join(joinArrays);
        if (res)
          res = this.extendTranslation(res, keys, options, lastKey);
      } else {
        let usedDefault = false;
        let usedKey = false;
        const needsPluralHandling = options.count !== void 0 && typeof options.count !== "string";
        const hasDefaultValue = Translator.hasDefaultValue(options);
        const defaultValueSuffix = needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, options) : "";
        const defaultValueSuffixOrdinalFallback = options.ordinal && needsPluralHandling ? this.pluralResolver.getSuffix(lng, options.count, {
          ordinal: false
        }) : "";
        const defaultValue2 = options[`defaultValue${defaultValueSuffix}`] || options[`defaultValue${defaultValueSuffixOrdinalFallback}`] || options.defaultValue;
        if (!this.isValidLookup(res) && hasDefaultValue) {
          usedDefault = true;
          res = defaultValue2;
        }
        if (!this.isValidLookup(res)) {
          usedKey = true;
          res = key;
        }
        const missingKeyNoValueFallbackToKey = options.missingKeyNoValueFallbackToKey || this.options.missingKeyNoValueFallbackToKey;
        const resForMissing = missingKeyNoValueFallbackToKey && usedKey ? void 0 : res;
        const updateMissing = hasDefaultValue && defaultValue2 !== res && this.options.updateMissing;
        if (usedKey || usedDefault || updateMissing) {
          this.logger.log(updateMissing ? "updateKey" : "missingKey", lng, namespace, key, updateMissing ? defaultValue2 : res);
          if (keySeparator) {
            const fk = this.resolve(key, {
              ...options,
              keySeparator: false
            });
            if (fk && fk.res)
              this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.");
          }
          let lngs = [];
          const fallbackLngs = this.languageUtils.getFallbackCodes(this.options.fallbackLng, options.lng || this.language);
          if (this.options.saveMissingTo === "fallback" && fallbackLngs && fallbackLngs[0]) {
            for (let i2 = 0; i2 < fallbackLngs.length; i2++) {
              lngs.push(fallbackLngs[i2]);
            }
          } else if (this.options.saveMissingTo === "all") {
            lngs = this.languageUtils.toResolveHierarchy(options.lng || this.language);
          } else {
            lngs.push(options.lng || this.language);
          }
          const send = (l2, k2, specificDefaultValue) => {
            const defaultForMissing = hasDefaultValue && specificDefaultValue !== res ? specificDefaultValue : resForMissing;
            if (this.options.missingKeyHandler) {
              this.options.missingKeyHandler(l2, namespace, k2, defaultForMissing, updateMissing, options);
            } else if (this.backendConnector && this.backendConnector.saveMissing) {
              this.backendConnector.saveMissing(l2, namespace, k2, defaultForMissing, updateMissing, options);
            }
            this.emit("missingKey", l2, namespace, k2, res);
          };
          if (this.options.saveMissing) {
            if (this.options.saveMissingPlurals && needsPluralHandling) {
              lngs.forEach((language) => {
                this.pluralResolver.getSuffixes(language, options).forEach((suffix) => {
                  send([language], key + suffix, options[`defaultValue${suffix}`] || defaultValue2);
                });
              });
            } else {
              send(lngs, key, defaultValue2);
            }
          }
        }
        res = this.extendTranslation(res, keys, options, resolved, lastKey);
        if (usedKey && res === key && this.options.appendNamespaceToMissingKey)
          res = `${namespace}:${key}`;
        if ((usedKey || usedDefault) && this.options.parseMissingKeyHandler) {
          if (this.options.compatibilityAPI !== "v1") {
            res = this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey ? `${namespace}:${key}` : key, usedDefault ? res : void 0);
          } else {
            res = this.options.parseMissingKeyHandler(res);
          }
        }
      }
      if (returnDetails) {
        resolved.res = res;
        return resolved;
      }
      return res;
    }
    extendTranslation(res, key, options, resolved, lastKey) {
      var _this = this;
      if (this.i18nFormat && this.i18nFormat.parse) {
        res = this.i18nFormat.parse(res, {
          ...this.options.interpolation.defaultVariables,
          ...options
        }, resolved.usedLng, resolved.usedNS, resolved.usedKey, {
          resolved
        });
      } else if (!options.skipInterpolation) {
        if (options.interpolation)
          this.interpolator.init({
            ...options,
            ...{
              interpolation: {
                ...this.options.interpolation,
                ...options.interpolation
              }
            }
          });
        const skipOnVariables = typeof res === "string" && (options && options.interpolation && options.interpolation.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables);
        let nestBef;
        if (skipOnVariables) {
          const nb = res.match(this.interpolator.nestingRegexp);
          nestBef = nb && nb.length;
        }
        let data = options.replace && typeof options.replace !== "string" ? options.replace : options;
        if (this.options.interpolation.defaultVariables)
          data = {
            ...this.options.interpolation.defaultVariables,
            ...data
          };
        res = this.interpolator.interpolate(res, data, options.lng || this.language, options);
        if (skipOnVariables) {
          const na = res.match(this.interpolator.nestingRegexp);
          const nestAft = na && na.length;
          if (nestBef < nestAft)
            options.nest = false;
        }
        if (!options.lng && this.options.compatibilityAPI !== "v1" && resolved && resolved.res)
          options.lng = resolved.usedLng;
        if (options.nest !== false)
          res = this.interpolator.nest(res, function() {
            for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
              args[_key] = arguments[_key];
            }
            if (lastKey && lastKey[0] === args[0] && !options.context) {
              _this.logger.warn(`It seems you are nesting recursively key: ${args[0]} in key: ${key[0]}`);
              return null;
            }
            return _this.translate(...args, key);
          }, options);
        if (options.interpolation)
          this.interpolator.reset();
      }
      const postProcess = options.postProcess || this.options.postProcess;
      const postProcessorNames = typeof postProcess === "string" ? [postProcess] : postProcess;
      if (res !== void 0 && res !== null && postProcessorNames && postProcessorNames.length && options.applyPostProcessor !== false) {
        res = postProcessor.handle(postProcessorNames, res, key, this.options && this.options.postProcessPassResolved ? {
          i18nResolved: resolved,
          ...options
        } : options, this);
      }
      return res;
    }
    resolve(keys) {
      let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      let found;
      let usedKey;
      let exactUsedKey;
      let usedLng;
      let usedNS;
      if (typeof keys === "string")
        keys = [keys];
      keys.forEach((k2) => {
        if (this.isValidLookup(found))
          return;
        const extracted = this.extractFromKey(k2, options);
        const key = extracted.key;
        usedKey = key;
        let namespaces = extracted.namespaces;
        if (this.options.fallbackNS)
          namespaces = namespaces.concat(this.options.fallbackNS);
        const needsPluralHandling = options.count !== void 0 && typeof options.count !== "string";
        const needsZeroSuffixLookup = needsPluralHandling && !options.ordinal && options.count === 0 && this.pluralResolver.shouldUseIntlApi();
        const needsContextHandling = options.context !== void 0 && (typeof options.context === "string" || typeof options.context === "number") && options.context !== "";
        const codes = options.lngs ? options.lngs : this.languageUtils.toResolveHierarchy(options.lng || this.language, options.fallbackLng);
        namespaces.forEach((ns) => {
          if (this.isValidLookup(found))
            return;
          usedNS = ns;
          if (!checkedLoadedFor[`${codes[0]}-${ns}`] && this.utils && this.utils.hasLoadedNamespace && !this.utils.hasLoadedNamespace(usedNS)) {
            checkedLoadedFor[`${codes[0]}-${ns}`] = true;
            this.logger.warn(`key "${usedKey}" for languages "${codes.join(", ")}" won't get resolved as namespace "${usedNS}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
          }
          codes.forEach((code) => {
            if (this.isValidLookup(found))
              return;
            usedLng = code;
            const finalKeys = [key];
            if (this.i18nFormat && this.i18nFormat.addLookupKeys) {
              this.i18nFormat.addLookupKeys(finalKeys, key, code, ns, options);
            } else {
              let pluralSuffix;
              if (needsPluralHandling)
                pluralSuffix = this.pluralResolver.getSuffix(code, options.count, options);
              const zeroSuffix = `${this.options.pluralSeparator}zero`;
              const ordinalPrefix = `${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;
              if (needsPluralHandling) {
                finalKeys.push(key + pluralSuffix);
                if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
                  finalKeys.push(key + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
                }
                if (needsZeroSuffixLookup) {
                  finalKeys.push(key + zeroSuffix);
                }
              }
              if (needsContextHandling) {
                const contextKey = `${key}${this.options.contextSeparator}${options.context}`;
                finalKeys.push(contextKey);
                if (needsPluralHandling) {
                  finalKeys.push(contextKey + pluralSuffix);
                  if (options.ordinal && pluralSuffix.indexOf(ordinalPrefix) === 0) {
                    finalKeys.push(contextKey + pluralSuffix.replace(ordinalPrefix, this.options.pluralSeparator));
                  }
                  if (needsZeroSuffixLookup) {
                    finalKeys.push(contextKey + zeroSuffix);
                  }
                }
              }
            }
            let possibleKey;
            while (possibleKey = finalKeys.pop()) {
              if (!this.isValidLookup(found)) {
                exactUsedKey = possibleKey;
                found = this.getResource(code, ns, possibleKey, options);
              }
            }
          });
        });
      });
      return {
        res: found,
        usedKey,
        exactUsedKey,
        usedLng,
        usedNS
      };
    }
    isValidLookup(res) {
      return res !== void 0 && !(!this.options.returnNull && res === null) && !(!this.options.returnEmptyString && res === "");
    }
    getResource(code, ns, key) {
      let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
      if (this.i18nFormat && this.i18nFormat.getResource)
        return this.i18nFormat.getResource(code, ns, key, options);
      return this.resourceStore.getResource(code, ns, key, options);
    }
    static hasDefaultValue(options) {
      const prefix = "defaultValue";
      for (const option in options) {
        if (Object.prototype.hasOwnProperty.call(options, option) && prefix === option.substring(0, prefix.length) && void 0 !== options[option]) {
          return true;
        }
      }
      return false;
    }
  }
  function capitalize(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
  }
  class LanguageUtil {
    constructor(options) {
      this.options = options;
      this.supportedLngs = this.options.supportedLngs || false;
      this.logger = baseLogger.create("languageUtils");
    }
    getScriptPartFromCode(code) {
      code = getCleanedCode(code);
      if (!code || code.indexOf("-") < 0)
        return null;
      const p2 = code.split("-");
      if (p2.length === 2)
        return null;
      p2.pop();
      if (p2[p2.length - 1].toLowerCase() === "x")
        return null;
      return this.formatLanguageCode(p2.join("-"));
    }
    getLanguagePartFromCode(code) {
      code = getCleanedCode(code);
      if (!code || code.indexOf("-") < 0)
        return code;
      const p2 = code.split("-");
      return this.formatLanguageCode(p2[0]);
    }
    formatLanguageCode(code) {
      if (typeof code === "string" && code.indexOf("-") > -1) {
        const specialCases = ["hans", "hant", "latn", "cyrl", "cans", "mong", "arab"];
        let p2 = code.split("-");
        if (this.options.lowerCaseLng) {
          p2 = p2.map((part) => part.toLowerCase());
        } else if (p2.length === 2) {
          p2[0] = p2[0].toLowerCase();
          p2[1] = p2[1].toUpperCase();
          if (specialCases.indexOf(p2[1].toLowerCase()) > -1)
            p2[1] = capitalize(p2[1].toLowerCase());
        } else if (p2.length === 3) {
          p2[0] = p2[0].toLowerCase();
          if (p2[1].length === 2)
            p2[1] = p2[1].toUpperCase();
          if (p2[0] !== "sgn" && p2[2].length === 2)
            p2[2] = p2[2].toUpperCase();
          if (specialCases.indexOf(p2[1].toLowerCase()) > -1)
            p2[1] = capitalize(p2[1].toLowerCase());
          if (specialCases.indexOf(p2[2].toLowerCase()) > -1)
            p2[2] = capitalize(p2[2].toLowerCase());
        }
        return p2.join("-");
      }
      return this.options.cleanCode || this.options.lowerCaseLng ? code.toLowerCase() : code;
    }
    isSupportedCode(code) {
      if (this.options.load === "languageOnly" || this.options.nonExplicitSupportedLngs) {
        code = this.getLanguagePartFromCode(code);
      }
      return !this.supportedLngs || !this.supportedLngs.length || this.supportedLngs.indexOf(code) > -1;
    }
    getBestMatchFromCodes(codes) {
      if (!codes)
        return null;
      let found;
      codes.forEach((code) => {
        if (found)
          return;
        const cleanedLng = this.formatLanguageCode(code);
        if (!this.options.supportedLngs || this.isSupportedCode(cleanedLng))
          found = cleanedLng;
      });
      if (!found && this.options.supportedLngs) {
        codes.forEach((code) => {
          if (found)
            return;
          const lngOnly = this.getLanguagePartFromCode(code);
          if (this.isSupportedCode(lngOnly))
            return found = lngOnly;
          found = this.options.supportedLngs.find((supportedLng) => {
            if (supportedLng === lngOnly)
              return supportedLng;
            if (supportedLng.indexOf("-") < 0 && lngOnly.indexOf("-") < 0)
              return;
            if (supportedLng.indexOf(lngOnly) === 0)
              return supportedLng;
          });
        });
      }
      if (!found)
        found = this.getFallbackCodes(this.options.fallbackLng)[0];
      return found;
    }
    getFallbackCodes(fallbacks, code) {
      if (!fallbacks)
        return [];
      if (typeof fallbacks === "function")
        fallbacks = fallbacks(code);
      if (typeof fallbacks === "string")
        fallbacks = [fallbacks];
      if (Object.prototype.toString.apply(fallbacks) === "[object Array]")
        return fallbacks;
      if (!code)
        return fallbacks.default || [];
      let found = fallbacks[code];
      if (!found)
        found = fallbacks[this.getScriptPartFromCode(code)];
      if (!found)
        found = fallbacks[this.formatLanguageCode(code)];
      if (!found)
        found = fallbacks[this.getLanguagePartFromCode(code)];
      if (!found)
        found = fallbacks.default;
      return found || [];
    }
    toResolveHierarchy(code, fallbackCode) {
      const fallbackCodes = this.getFallbackCodes(fallbackCode || this.options.fallbackLng || [], code);
      const codes = [];
      const addCode = (c2) => {
        if (!c2)
          return;
        if (this.isSupportedCode(c2)) {
          codes.push(c2);
        } else {
          this.logger.warn(`rejecting language code not found in supportedLngs: ${c2}`);
        }
      };
      if (typeof code === "string" && (code.indexOf("-") > -1 || code.indexOf("_") > -1)) {
        if (this.options.load !== "languageOnly")
          addCode(this.formatLanguageCode(code));
        if (this.options.load !== "languageOnly" && this.options.load !== "currentOnly")
          addCode(this.getScriptPartFromCode(code));
        if (this.options.load !== "currentOnly")
          addCode(this.getLanguagePartFromCode(code));
      } else if (typeof code === "string") {
        addCode(this.formatLanguageCode(code));
      }
      fallbackCodes.forEach((fc) => {
        if (codes.indexOf(fc) < 0)
          addCode(this.formatLanguageCode(fc));
      });
      return codes;
    }
  }
  let sets = [{
    lngs: ["ach", "ak", "am", "arn", "br", "fil", "gun", "ln", "mfe", "mg", "mi", "oc", "pt", "pt-BR", "tg", "tl", "ti", "tr", "uz", "wa"],
    nr: [1, 2],
    fc: 1
  }, {
    lngs: ["af", "an", "ast", "az", "bg", "bn", "ca", "da", "de", "dev", "el", "en", "eo", "es", "et", "eu", "fi", "fo", "fur", "fy", "gl", "gu", "ha", "hi", "hu", "hy", "ia", "it", "kk", "kn", "ku", "lb", "mai", "ml", "mn", "mr", "nah", "nap", "nb", "ne", "nl", "nn", "no", "nso", "pa", "pap", "pms", "ps", "pt-PT", "rm", "sco", "se", "si", "so", "son", "sq", "sv", "sw", "ta", "te", "tk", "ur", "yo"],
    nr: [1, 2],
    fc: 2
  }, {
    lngs: ["ay", "bo", "cgg", "fa", "ht", "id", "ja", "jbo", "ka", "km", "ko", "ky", "lo", "ms", "sah", "su", "th", "tt", "ug", "vi", "wo", "zh"],
    nr: [1],
    fc: 3
  }, {
    lngs: ["be", "bs", "cnr", "dz", "hr", "ru", "sr", "uk"],
    nr: [1, 2, 5],
    fc: 4
  }, {
    lngs: ["ar"],
    nr: [0, 1, 2, 3, 11, 100],
    fc: 5
  }, {
    lngs: ["cs", "sk"],
    nr: [1, 2, 5],
    fc: 6
  }, {
    lngs: ["csb", "pl"],
    nr: [1, 2, 5],
    fc: 7
  }, {
    lngs: ["cy"],
    nr: [1, 2, 3, 8],
    fc: 8
  }, {
    lngs: ["fr"],
    nr: [1, 2],
    fc: 9
  }, {
    lngs: ["ga"],
    nr: [1, 2, 3, 7, 11],
    fc: 10
  }, {
    lngs: ["gd"],
    nr: [1, 2, 3, 20],
    fc: 11
  }, {
    lngs: ["is"],
    nr: [1, 2],
    fc: 12
  }, {
    lngs: ["jv"],
    nr: [0, 1],
    fc: 13
  }, {
    lngs: ["kw"],
    nr: [1, 2, 3, 4],
    fc: 14
  }, {
    lngs: ["lt"],
    nr: [1, 2, 10],
    fc: 15
  }, {
    lngs: ["lv"],
    nr: [1, 2, 0],
    fc: 16
  }, {
    lngs: ["mk"],
    nr: [1, 2],
    fc: 17
  }, {
    lngs: ["mnk"],
    nr: [0, 1, 2],
    fc: 18
  }, {
    lngs: ["mt"],
    nr: [1, 2, 11, 20],
    fc: 19
  }, {
    lngs: ["or"],
    nr: [2, 1],
    fc: 2
  }, {
    lngs: ["ro"],
    nr: [1, 2, 20],
    fc: 20
  }, {
    lngs: ["sl"],
    nr: [5, 1, 2, 3],
    fc: 21
  }, {
    lngs: ["he", "iw"],
    nr: [1, 2, 20, 21],
    fc: 22
  }];
  let _rulesPluralsTypes = {
    1: function(n2) {
      return Number(n2 > 1);
    },
    2: function(n2) {
      return Number(n2 != 1);
    },
    3: function(n2) {
      return 0;
    },
    4: function(n2) {
      return Number(n2 % 10 == 1 && n2 % 100 != 11 ? 0 : n2 % 10 >= 2 && n2 % 10 <= 4 && (n2 % 100 < 10 || n2 % 100 >= 20) ? 1 : 2);
    },
    5: function(n2) {
      return Number(n2 == 0 ? 0 : n2 == 1 ? 1 : n2 == 2 ? 2 : n2 % 100 >= 3 && n2 % 100 <= 10 ? 3 : n2 % 100 >= 11 ? 4 : 5);
    },
    6: function(n2) {
      return Number(n2 == 1 ? 0 : n2 >= 2 && n2 <= 4 ? 1 : 2);
    },
    7: function(n2) {
      return Number(n2 == 1 ? 0 : n2 % 10 >= 2 && n2 % 10 <= 4 && (n2 % 100 < 10 || n2 % 100 >= 20) ? 1 : 2);
    },
    8: function(n2) {
      return Number(n2 == 1 ? 0 : n2 == 2 ? 1 : n2 != 8 && n2 != 11 ? 2 : 3);
    },
    9: function(n2) {
      return Number(n2 >= 2);
    },
    10: function(n2) {
      return Number(n2 == 1 ? 0 : n2 == 2 ? 1 : n2 < 7 ? 2 : n2 < 11 ? 3 : 4);
    },
    11: function(n2) {
      return Number(n2 == 1 || n2 == 11 ? 0 : n2 == 2 || n2 == 12 ? 1 : n2 > 2 && n2 < 20 ? 2 : 3);
    },
    12: function(n2) {
      return Number(n2 % 10 != 1 || n2 % 100 == 11);
    },
    13: function(n2) {
      return Number(n2 !== 0);
    },
    14: function(n2) {
      return Number(n2 == 1 ? 0 : n2 == 2 ? 1 : n2 == 3 ? 2 : 3);
    },
    15: function(n2) {
      return Number(n2 % 10 == 1 && n2 % 100 != 11 ? 0 : n2 % 10 >= 2 && (n2 % 100 < 10 || n2 % 100 >= 20) ? 1 : 2);
    },
    16: function(n2) {
      return Number(n2 % 10 == 1 && n2 % 100 != 11 ? 0 : n2 !== 0 ? 1 : 2);
    },
    17: function(n2) {
      return Number(n2 == 1 || n2 % 10 == 1 && n2 % 100 != 11 ? 0 : 1);
    },
    18: function(n2) {
      return Number(n2 == 0 ? 0 : n2 == 1 ? 1 : 2);
    },
    19: function(n2) {
      return Number(n2 == 1 ? 0 : n2 == 0 || n2 % 100 > 1 && n2 % 100 < 11 ? 1 : n2 % 100 > 10 && n2 % 100 < 20 ? 2 : 3);
    },
    20: function(n2) {
      return Number(n2 == 1 ? 0 : n2 == 0 || n2 % 100 > 0 && n2 % 100 < 20 ? 1 : 2);
    },
    21: function(n2) {
      return Number(n2 % 100 == 1 ? 1 : n2 % 100 == 2 ? 2 : n2 % 100 == 3 || n2 % 100 == 4 ? 3 : 0);
    },
    22: function(n2) {
      return Number(n2 == 1 ? 0 : n2 == 2 ? 1 : (n2 < 0 || n2 > 10) && n2 % 10 == 0 ? 2 : 3);
    }
  };
  const nonIntlVersions = ["v1", "v2", "v3"];
  const intlVersions = ["v4"];
  const suffixesOrder = {
    zero: 0,
    one: 1,
    two: 2,
    few: 3,
    many: 4,
    other: 5
  };
  function createRules() {
    const rules = {};
    sets.forEach((set2) => {
      set2.lngs.forEach((l2) => {
        rules[l2] = {
          numbers: set2.nr,
          plurals: _rulesPluralsTypes[set2.fc]
        };
      });
    });
    return rules;
  }
  class PluralResolver {
    constructor(languageUtils) {
      let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      this.languageUtils = languageUtils;
      this.options = options;
      this.logger = baseLogger.create("pluralResolver");
      if ((!this.options.compatibilityJSON || intlVersions.includes(this.options.compatibilityJSON)) && (typeof Intl === "undefined" || !Intl.PluralRules)) {
        this.options.compatibilityJSON = "v3";
        this.logger.error("Your environment seems not to be Intl API compatible, use an Intl.PluralRules polyfill. Will fallback to the compatibilityJSON v3 format handling.");
      }
      this.rules = createRules();
    }
    addRule(lng, obj) {
      this.rules[lng] = obj;
    }
    getRule(code) {
      let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      if (this.shouldUseIntlApi()) {
        try {
          return new Intl.PluralRules(getCleanedCode(code), {
            type: options.ordinal ? "ordinal" : "cardinal"
          });
        } catch {
          return;
        }
      }
      return this.rules[code] || this.rules[this.languageUtils.getLanguagePartFromCode(code)];
    }
    needsPlural(code) {
      let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      const rule = this.getRule(code, options);
      if (this.shouldUseIntlApi()) {
        return rule && rule.resolvedOptions().pluralCategories.length > 1;
      }
      return rule && rule.numbers.length > 1;
    }
    getPluralFormsOfKey(code, key) {
      let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      return this.getSuffixes(code, options).map((suffix) => `${key}${suffix}`);
    }
    getSuffixes(code) {
      let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      const rule = this.getRule(code, options);
      if (!rule) {
        return [];
      }
      if (this.shouldUseIntlApi()) {
        return rule.resolvedOptions().pluralCategories.sort((pluralCategory1, pluralCategory2) => suffixesOrder[pluralCategory1] - suffixesOrder[pluralCategory2]).map((pluralCategory) => `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${pluralCategory}`);
      }
      return rule.numbers.map((number) => this.getSuffix(code, number, options));
    }
    getSuffix(code, count) {
      let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      const rule = this.getRule(code, options);
      if (rule) {
        if (this.shouldUseIntlApi()) {
          return `${this.options.prepend}${options.ordinal ? `ordinal${this.options.prepend}` : ""}${rule.select(count)}`;
        }
        return this.getSuffixRetroCompatible(rule, count);
      }
      this.logger.warn(`no plural rule found for: ${code}`);
      return "";
    }
    getSuffixRetroCompatible(rule, count) {
      const idx = rule.noAbs ? rule.plurals(count) : rule.plurals(Math.abs(count));
      let suffix = rule.numbers[idx];
      if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
        if (suffix === 2) {
          suffix = "plural";
        } else if (suffix === 1) {
          suffix = "";
        }
      }
      const returnSuffix = () => this.options.prepend && suffix.toString() ? this.options.prepend + suffix.toString() : suffix.toString();
      if (this.options.compatibilityJSON === "v1") {
        if (suffix === 1)
          return "";
        if (typeof suffix === "number")
          return `_plural_${suffix.toString()}`;
        return returnSuffix();
      } else if (this.options.compatibilityJSON === "v2") {
        return returnSuffix();
      } else if (this.options.simplifyPluralSuffix && rule.numbers.length === 2 && rule.numbers[0] === 1) {
        return returnSuffix();
      }
      return this.options.prepend && idx.toString() ? this.options.prepend + idx.toString() : idx.toString();
    }
    shouldUseIntlApi() {
      return !nonIntlVersions.includes(this.options.compatibilityJSON);
    }
  }
  function deepFindWithDefaults(data, defaultData2, key) {
    let keySeparator = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : ".";
    let ignoreJSONStructure = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true;
    let path = getPathWithDefaults(data, defaultData2, key);
    if (!path && ignoreJSONStructure && typeof key === "string") {
      path = deepFind(data, key, keySeparator);
      if (path === void 0)
        path = deepFind(defaultData2, key, keySeparator);
    }
    return path;
  }
  class Interpolator {
    constructor() {
      let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      this.logger = baseLogger.create("interpolator");
      this.options = options;
      this.format = options.interpolation && options.interpolation.format || ((value) => value);
      this.init(options);
    }
    init() {
      let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      if (!options.interpolation)
        options.interpolation = {
          escapeValue: true
        };
      const iOpts = options.interpolation;
      this.escape = iOpts.escape !== void 0 ? iOpts.escape : escape$1;
      this.escapeValue = iOpts.escapeValue !== void 0 ? iOpts.escapeValue : true;
      this.useRawValueToEscape = iOpts.useRawValueToEscape !== void 0 ? iOpts.useRawValueToEscape : false;
      this.prefix = iOpts.prefix ? regexEscape(iOpts.prefix) : iOpts.prefixEscaped || "{{";
      this.suffix = iOpts.suffix ? regexEscape(iOpts.suffix) : iOpts.suffixEscaped || "}}";
      this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ",";
      this.unescapePrefix = iOpts.unescapeSuffix ? "" : iOpts.unescapePrefix || "-";
      this.unescapeSuffix = this.unescapePrefix ? "" : iOpts.unescapeSuffix || "";
      this.nestingPrefix = iOpts.nestingPrefix ? regexEscape(iOpts.nestingPrefix) : iOpts.nestingPrefixEscaped || regexEscape("$t(");
      this.nestingSuffix = iOpts.nestingSuffix ? regexEscape(iOpts.nestingSuffix) : iOpts.nestingSuffixEscaped || regexEscape(")");
      this.nestingOptionsSeparator = iOpts.nestingOptionsSeparator ? iOpts.nestingOptionsSeparator : iOpts.nestingOptionsSeparator || ",";
      this.maxReplaces = iOpts.maxReplaces ? iOpts.maxReplaces : 1e3;
      this.alwaysFormat = iOpts.alwaysFormat !== void 0 ? iOpts.alwaysFormat : false;
      this.resetRegExp();
    }
    reset() {
      if (this.options)
        this.init(this.options);
    }
    resetRegExp() {
      const regexpStr = `${this.prefix}(.+?)${this.suffix}`;
      this.regexp = new RegExp(regexpStr, "g");
      const regexpUnescapeStr = `${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`;
      this.regexpUnescape = new RegExp(regexpUnescapeStr, "g");
      const nestingRegexpStr = `${this.nestingPrefix}(.+?)${this.nestingSuffix}`;
      this.nestingRegexp = new RegExp(nestingRegexpStr, "g");
    }
    interpolate(str, data, lng, options) {
      let match;
      let value;
      let replaces;
      const defaultData2 = this.options && this.options.interpolation && this.options.interpolation.defaultVariables || {};
      function regexSafe(val) {
        return val.replace(/\$/g, "$$$$");
      }
      const handleFormat = (key) => {
        if (key.indexOf(this.formatSeparator) < 0) {
          const path = deepFindWithDefaults(data, defaultData2, key, this.options.keySeparator, this.options.ignoreJSONStructure);
          return this.alwaysFormat ? this.format(path, void 0, lng, {
            ...options,
            ...data,
            interpolationkey: key
          }) : path;
        }
        const p2 = key.split(this.formatSeparator);
        const k2 = p2.shift().trim();
        const f2 = p2.join(this.formatSeparator).trim();
        return this.format(deepFindWithDefaults(data, defaultData2, k2, this.options.keySeparator, this.options.ignoreJSONStructure), f2, lng, {
          ...options,
          ...data,
          interpolationkey: k2
        });
      };
      this.resetRegExp();
      const missingInterpolationHandler = options && options.missingInterpolationHandler || this.options.missingInterpolationHandler;
      const skipOnVariables = options && options.interpolation && options.interpolation.skipOnVariables !== void 0 ? options.interpolation.skipOnVariables : this.options.interpolation.skipOnVariables;
      const todos = [{
        regex: this.regexpUnescape,
        safeValue: (val) => regexSafe(val)
      }, {
        regex: this.regexp,
        safeValue: (val) => this.escapeValue ? regexSafe(this.escape(val)) : regexSafe(val)
      }];
      todos.forEach((todo) => {
        replaces = 0;
        while (match = todo.regex.exec(str)) {
          const matchedVar = match[1].trim();
          value = handleFormat(matchedVar);
          if (value === void 0) {
            if (typeof missingInterpolationHandler === "function") {
              const temp = missingInterpolationHandler(str, match, options);
              value = typeof temp === "string" ? temp : "";
            } else if (options && Object.prototype.hasOwnProperty.call(options, matchedVar)) {
              value = "";
            } else if (skipOnVariables) {
              value = match[0];
              continue;
            } else {
              this.logger.warn(`missed to pass in variable ${matchedVar} for interpolating ${str}`);
              value = "";
            }
          } else if (typeof value !== "string" && !this.useRawValueToEscape) {
            value = makeString(value);
          }
          const safeValue = todo.safeValue(value);
          str = str.replace(match[0], safeValue);
          if (skipOnVariables) {
            todo.regex.lastIndex += value.length;
            todo.regex.lastIndex -= match[0].length;
          } else {
            todo.regex.lastIndex = 0;
          }
          replaces++;
          if (replaces >= this.maxReplaces) {
            break;
          }
        }
      });
      return str;
    }
    nest(str, fc) {
      let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      let match;
      let value;
      let clonedOptions;
      function handleHasOptions(key, inheritedOptions) {
        const sep = this.nestingOptionsSeparator;
        if (key.indexOf(sep) < 0)
          return key;
        const c2 = key.split(new RegExp(`${sep}[ ]*{`));
        let optionsString = `{${c2[1]}`;
        key = c2[0];
        optionsString = this.interpolate(optionsString, clonedOptions);
        const matchedSingleQuotes = optionsString.match(/'/g);
        const matchedDoubleQuotes = optionsString.match(/"/g);
        if (matchedSingleQuotes && matchedSingleQuotes.length % 2 === 0 && !matchedDoubleQuotes || matchedDoubleQuotes.length % 2 !== 0) {
          optionsString = optionsString.replace(/'/g, '"');
        }
        try {
          clonedOptions = JSON.parse(optionsString);
          if (inheritedOptions)
            clonedOptions = {
              ...inheritedOptions,
              ...clonedOptions
            };
        } catch (e2) {
          this.logger.warn(`failed parsing options string in nesting for key ${key}`, e2);
          return `${key}${sep}${optionsString}`;
        }
        delete clonedOptions.defaultValue;
        return key;
      }
      while (match = this.nestingRegexp.exec(str)) {
        let formatters = [];
        clonedOptions = {
          ...options
        };
        clonedOptions = clonedOptions.replace && typeof clonedOptions.replace !== "string" ? clonedOptions.replace : clonedOptions;
        clonedOptions.applyPostProcessor = false;
        delete clonedOptions.defaultValue;
        let doReduce = false;
        if (match[0].indexOf(this.formatSeparator) !== -1 && !/{.*}/.test(match[1])) {
          const r2 = match[1].split(this.formatSeparator).map((elem) => elem.trim());
          match[1] = r2.shift();
          formatters = r2;
          doReduce = true;
        }
        value = fc(handleHasOptions.call(this, match[1].trim(), clonedOptions), clonedOptions);
        if (value && match[0] === str && typeof value !== "string")
          return value;
        if (typeof value !== "string")
          value = makeString(value);
        if (!value) {
          this.logger.warn(`missed to resolve ${match[1]} for nesting ${str}`);
          value = "";
        }
        if (doReduce) {
          value = formatters.reduce((v2, f2) => this.format(v2, f2, options.lng, {
            ...options,
            interpolationkey: match[1].trim()
          }), value.trim());
        }
        str = str.replace(match[0], value);
        this.regexp.lastIndex = 0;
      }
      return str;
    }
  }
  function parseFormatStr(formatStr) {
    let formatName = formatStr.toLowerCase().trim();
    const formatOptions = {};
    if (formatStr.indexOf("(") > -1) {
      const p2 = formatStr.split("(");
      formatName = p2[0].toLowerCase().trim();
      const optStr = p2[1].substring(0, p2[1].length - 1);
      if (formatName === "currency" && optStr.indexOf(":") < 0) {
        if (!formatOptions.currency)
          formatOptions.currency = optStr.trim();
      } else if (formatName === "relativetime" && optStr.indexOf(":") < 0) {
        if (!formatOptions.range)
          formatOptions.range = optStr.trim();
      } else {
        const opts = optStr.split(";");
        opts.forEach((opt) => {
          if (!opt)
            return;
          const [key, ...rest] = opt.split(":");
          const val = rest.join(":").trim().replace(/^'+|'+$/g, "");
          if (!formatOptions[key.trim()])
            formatOptions[key.trim()] = val;
          if (val === "false")
            formatOptions[key.trim()] = false;
          if (val === "true")
            formatOptions[key.trim()] = true;
          if (!isNaN(val))
            formatOptions[key.trim()] = parseInt(val, 10);
        });
      }
    }
    return {
      formatName,
      formatOptions
    };
  }
  function createCachedFormatter(fn2) {
    const cache = {};
    return function invokeFormatter(val, lng, options) {
      const key = lng + JSON.stringify(options);
      let formatter = cache[key];
      if (!formatter) {
        formatter = fn2(getCleanedCode(lng), options);
        cache[key] = formatter;
      }
      return formatter(val);
    };
  }
  class Formatter {
    constructor() {
      let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      this.logger = baseLogger.create("formatter");
      this.options = options;
      this.formats = {
        number: createCachedFormatter((lng, opt) => {
          const formatter = new Intl.NumberFormat(lng, {
            ...opt
          });
          return (val) => formatter.format(val);
        }),
        currency: createCachedFormatter((lng, opt) => {
          const formatter = new Intl.NumberFormat(lng, {
            ...opt,
            style: "currency"
          });
          return (val) => formatter.format(val);
        }),
        datetime: createCachedFormatter((lng, opt) => {
          const formatter = new Intl.DateTimeFormat(lng, {
            ...opt
          });
          return (val) => formatter.format(val);
        }),
        relativetime: createCachedFormatter((lng, opt) => {
          const formatter = new Intl.RelativeTimeFormat(lng, {
            ...opt
          });
          return (val) => formatter.format(val, opt.range || "day");
        }),
        list: createCachedFormatter((lng, opt) => {
          const formatter = new Intl.ListFormat(lng, {
            ...opt
          });
          return (val) => formatter.format(val);
        })
      };
      this.init(options);
    }
    init(services) {
      let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {
        interpolation: {}
      };
      const iOpts = options.interpolation;
      this.formatSeparator = iOpts.formatSeparator ? iOpts.formatSeparator : iOpts.formatSeparator || ",";
    }
    add(name2, fc) {
      this.formats[name2.toLowerCase().trim()] = fc;
    }
    addCached(name2, fc) {
      this.formats[name2.toLowerCase().trim()] = createCachedFormatter(fc);
    }
    format(value, format, lng) {
      let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
      const formats = format.split(this.formatSeparator);
      const result = formats.reduce((mem, f2) => {
        const {
          formatName,
          formatOptions
        } = parseFormatStr(f2);
        if (this.formats[formatName]) {
          let formatted = mem;
          try {
            const valOptions = options && options.formatParams && options.formatParams[options.interpolationkey] || {};
            const l2 = valOptions.locale || valOptions.lng || options.locale || options.lng || lng;
            formatted = this.formats[formatName](mem, l2, {
              ...formatOptions,
              ...options,
              ...valOptions
            });
          } catch (error2) {
            this.logger.warn(error2);
          }
          return formatted;
        } else {
          this.logger.warn(`there was no format function for ${formatName}`);
        }
        return mem;
      }, value);
      return result;
    }
  }
  function removePending(q2, name2) {
    if (q2.pending[name2] !== void 0) {
      delete q2.pending[name2];
      q2.pendingCount--;
    }
  }
  class Connector extends EventEmitter$1 {
    constructor(backend, store, services) {
      let options = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : {};
      super();
      this.backend = backend;
      this.store = store;
      this.services = services;
      this.languageUtils = services.languageUtils;
      this.options = options;
      this.logger = baseLogger.create("backendConnector");
      this.waitingReads = [];
      this.maxParallelReads = options.maxParallelReads || 10;
      this.readingCalls = 0;
      this.maxRetries = options.maxRetries >= 0 ? options.maxRetries : 5;
      this.retryTimeout = options.retryTimeout >= 1 ? options.retryTimeout : 350;
      this.state = {};
      this.queue = [];
      if (this.backend && this.backend.init) {
        this.backend.init(services, options.backend, options);
      }
    }
    queueLoad(languages, namespaces, options, callback) {
      const toLoad = {};
      const pending = {};
      const toLoadLanguages = {};
      const toLoadNamespaces = {};
      languages.forEach((lng) => {
        let hasAllNamespaces = true;
        namespaces.forEach((ns) => {
          const name2 = `${lng}|${ns}`;
          if (!options.reload && this.store.hasResourceBundle(lng, ns)) {
            this.state[name2] = 2;
          } else if (this.state[name2] < 0)
            ;
          else if (this.state[name2] === 1) {
            if (pending[name2] === void 0)
              pending[name2] = true;
          } else {
            this.state[name2] = 1;
            hasAllNamespaces = false;
            if (pending[name2] === void 0)
              pending[name2] = true;
            if (toLoad[name2] === void 0)
              toLoad[name2] = true;
            if (toLoadNamespaces[ns] === void 0)
              toLoadNamespaces[ns] = true;
          }
        });
        if (!hasAllNamespaces)
          toLoadLanguages[lng] = true;
      });
      if (Object.keys(toLoad).length || Object.keys(pending).length) {
        this.queue.push({
          pending,
          pendingCount: Object.keys(pending).length,
          loaded: {},
          errors: [],
          callback
        });
      }
      return {
        toLoad: Object.keys(toLoad),
        pending: Object.keys(pending),
        toLoadLanguages: Object.keys(toLoadLanguages),
        toLoadNamespaces: Object.keys(toLoadNamespaces)
      };
    }
    loaded(name2, err, data) {
      const s2 = name2.split("|");
      const lng = s2[0];
      const ns = s2[1];
      if (err)
        this.emit("failedLoading", lng, ns, err);
      if (data) {
        this.store.addResourceBundle(lng, ns, data);
      }
      this.state[name2] = err ? -1 : 2;
      const loaded = {};
      this.queue.forEach((q2) => {
        pushPath(q2.loaded, [lng], ns);
        removePending(q2, name2);
        if (err)
          q2.errors.push(err);
        if (q2.pendingCount === 0 && !q2.done) {
          Object.keys(q2.loaded).forEach((l2) => {
            if (!loaded[l2])
              loaded[l2] = {};
            const loadedKeys = q2.loaded[l2];
            if (loadedKeys.length) {
              loadedKeys.forEach((n2) => {
                if (loaded[l2][n2] === void 0)
                  loaded[l2][n2] = true;
              });
            }
          });
          q2.done = true;
          if (q2.errors.length) {
            q2.callback(q2.errors);
          } else {
            q2.callback();
          }
        }
      });
      this.emit("loaded", loaded);
      this.queue = this.queue.filter((q2) => !q2.done);
    }
    read(lng, ns, fcName) {
      let tried = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0;
      let wait = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : this.retryTimeout;
      let callback = arguments.length > 5 ? arguments[5] : void 0;
      if (!lng.length)
        return callback(null, {});
      if (this.readingCalls >= this.maxParallelReads) {
        this.waitingReads.push({
          lng,
          ns,
          fcName,
          tried,
          wait,
          callback
        });
        return;
      }
      this.readingCalls++;
      const resolver = (err, data) => {
        this.readingCalls--;
        if (this.waitingReads.length > 0) {
          const next = this.waitingReads.shift();
          this.read(next.lng, next.ns, next.fcName, next.tried, next.wait, next.callback);
        }
        if (err && data && tried < this.maxRetries) {
          setTimeout(() => {
            this.read.call(this, lng, ns, fcName, tried + 1, wait * 2, callback);
          }, wait);
          return;
        }
        callback(err, data);
      };
      const fc = this.backend[fcName].bind(this.backend);
      if (fc.length === 2) {
        try {
          const r2 = fc(lng, ns);
          if (r2 && typeof r2.then === "function") {
            r2.then((data) => resolver(null, data)).catch(resolver);
          } else {
            resolver(null, r2);
          }
        } catch (err) {
          resolver(err);
        }
        return;
      }
      return fc(lng, ns, resolver);
    }
    prepareLoading(languages, namespaces) {
      let options = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
      let callback = arguments.length > 3 ? arguments[3] : void 0;
      if (!this.backend) {
        this.logger.warn("No backend was added via i18next.use. Will not load resources.");
        return callback && callback();
      }
      if (typeof languages === "string")
        languages = this.languageUtils.toResolveHierarchy(languages);
      if (typeof namespaces === "string")
        namespaces = [namespaces];
      const toLoad = this.queueLoad(languages, namespaces, options, callback);
      if (!toLoad.toLoad.length) {
        if (!toLoad.pending.length)
          callback();
        return null;
      }
      toLoad.toLoad.forEach((name2) => {
        this.loadOne(name2);
      });
    }
    load(languages, namespaces, callback) {
      this.prepareLoading(languages, namespaces, {}, callback);
    }
    reload(languages, namespaces, callback) {
      this.prepareLoading(languages, namespaces, {
        reload: true
      }, callback);
    }
    loadOne(name2) {
      let prefix = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "";
      const s2 = name2.split("|");
      const lng = s2[0];
      const ns = s2[1];
      this.read(lng, ns, "read", void 0, void 0, (err, data) => {
        if (err)
          this.logger.warn(`${prefix}loading namespace ${ns} for language ${lng} failed`, err);
        if (!err && data)
          this.logger.log(`${prefix}loaded namespace ${ns} for language ${lng}`, data);
        this.loaded(name2, err, data);
      });
    }
    saveMissing(languages, namespace, key, fallbackValue, isUpdate) {
      let options = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : {};
      let clb = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : () => {
      };
      if (this.services.utils && this.services.utils.hasLoadedNamespace && !this.services.utils.hasLoadedNamespace(namespace)) {
        this.logger.warn(`did not save key "${key}" as the namespace "${namespace}" was not yet loaded`, "This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");
        return;
      }
      if (key === void 0 || key === null || key === "")
        return;
      if (this.backend && this.backend.create) {
        const opts = {
          ...options,
          isUpdate
        };
        const fc = this.backend.create.bind(this.backend);
        if (fc.length < 6) {
          try {
            let r2;
            if (fc.length === 5) {
              r2 = fc(languages, namespace, key, fallbackValue, opts);
            } else {
              r2 = fc(languages, namespace, key, fallbackValue);
            }
            if (r2 && typeof r2.then === "function") {
              r2.then((data) => clb(null, data)).catch(clb);
            } else {
              clb(null, r2);
            }
          } catch (err) {
            clb(err);
          }
        } else {
          fc(languages, namespace, key, fallbackValue, clb, opts);
        }
      }
      if (!languages || !languages[0])
        return;
      this.store.addResource(languages[0], namespace, key, fallbackValue);
    }
  }
  function get$1() {
    return {
      debug: false,
      initImmediate: true,
      ns: ["translation"],
      defaultNS: ["translation"],
      fallbackLng: ["dev"],
      fallbackNS: false,
      supportedLngs: false,
      nonExplicitSupportedLngs: false,
      load: "all",
      preload: false,
      simplifyPluralSuffix: true,
      keySeparator: ".",
      nsSeparator: ":",
      pluralSeparator: "_",
      contextSeparator: "_",
      partialBundledLanguages: false,
      saveMissing: false,
      updateMissing: false,
      saveMissingTo: "fallback",
      saveMissingPlurals: true,
      missingKeyHandler: false,
      missingInterpolationHandler: false,
      postProcess: false,
      postProcessPassResolved: false,
      returnNull: false,
      returnEmptyString: true,
      returnObjects: false,
      joinArrays: false,
      returnedObjectHandler: false,
      parseMissingKeyHandler: false,
      appendNamespaceToMissingKey: false,
      appendNamespaceToCIMode: false,
      overloadTranslationOptionHandler: function handle(args) {
        let ret = {};
        if (typeof args[1] === "object")
          ret = args[1];
        if (typeof args[1] === "string")
          ret.defaultValue = args[1];
        if (typeof args[2] === "string")
          ret.tDescription = args[2];
        if (typeof args[2] === "object" || typeof args[3] === "object") {
          const options = args[3] || args[2];
          Object.keys(options).forEach((key) => {
            ret[key] = options[key];
          });
        }
        return ret;
      },
      interpolation: {
        escapeValue: true,
        format: (value, format, lng, options) => value,
        prefix: "{{",
        suffix: "}}",
        formatSeparator: ",",
        unescapePrefix: "-",
        nestingPrefix: "$t(",
        nestingSuffix: ")",
        nestingOptionsSeparator: ",",
        maxReplaces: 1e3,
        skipOnVariables: true
      }
    };
  }
  function transformOptions(options) {
    if (typeof options.ns === "string")
      options.ns = [options.ns];
    if (typeof options.fallbackLng === "string")
      options.fallbackLng = [options.fallbackLng];
    if (typeof options.fallbackNS === "string")
      options.fallbackNS = [options.fallbackNS];
    if (options.supportedLngs && options.supportedLngs.indexOf("cimode") < 0) {
      options.supportedLngs = options.supportedLngs.concat(["cimode"]);
    }
    return options;
  }
  function noop$1() {
  }
  function bindMemberFunctions(inst) {
    const mems = Object.getOwnPropertyNames(Object.getPrototypeOf(inst));
    mems.forEach((mem) => {
      if (typeof inst[mem] === "function") {
        inst[mem] = inst[mem].bind(inst);
      }
    });
  }
  class I18n extends EventEmitter$1 {
    constructor() {
      let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      let callback = arguments.length > 1 ? arguments[1] : void 0;
      super();
      this.options = transformOptions(options);
      this.services = {};
      this.logger = baseLogger;
      this.modules = {
        external: []
      };
      bindMemberFunctions(this);
      if (callback && !this.isInitialized && !options.isClone) {
        if (!this.options.initImmediate) {
          this.init(options, callback);
          return this;
        }
        setTimeout(() => {
          this.init(options, callback);
        }, 0);
      }
    }
    init() {
      var _this = this;
      let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      let callback = arguments.length > 1 ? arguments[1] : void 0;
      if (typeof options === "function") {
        callback = options;
        options = {};
      }
      if (!options.defaultNS && options.defaultNS !== false && options.ns) {
        if (typeof options.ns === "string") {
          options.defaultNS = options.ns;
        } else if (options.ns.indexOf("translation") < 0) {
          options.defaultNS = options.ns[0];
        }
      }
      const defOpts = get$1();
      this.options = {
        ...defOpts,
        ...this.options,
        ...transformOptions(options)
      };
      if (this.options.compatibilityAPI !== "v1") {
        this.options.interpolation = {
          ...defOpts.interpolation,
          ...this.options.interpolation
        };
      }
      if (options.keySeparator !== void 0) {
        this.options.userDefinedKeySeparator = options.keySeparator;
      }
      if (options.nsSeparator !== void 0) {
        this.options.userDefinedNsSeparator = options.nsSeparator;
      }
      function createClassOnDemand(ClassOrObject) {
        if (!ClassOrObject)
          return null;
        if (typeof ClassOrObject === "function")
          return new ClassOrObject();
        return ClassOrObject;
      }
      if (!this.options.isClone) {
        if (this.modules.logger) {
          baseLogger.init(createClassOnDemand(this.modules.logger), this.options);
        } else {
          baseLogger.init(null, this.options);
        }
        let formatter;
        if (this.modules.formatter) {
          formatter = this.modules.formatter;
        } else if (typeof Intl !== "undefined") {
          formatter = Formatter;
        }
        const lu = new LanguageUtil(this.options);
        this.store = new ResourceStore(this.options.resources, this.options);
        const s2 = this.services;
        s2.logger = baseLogger;
        s2.resourceStore = this.store;
        s2.languageUtils = lu;
        s2.pluralResolver = new PluralResolver(lu, {
          prepend: this.options.pluralSeparator,
          compatibilityJSON: this.options.compatibilityJSON,
          simplifyPluralSuffix: this.options.simplifyPluralSuffix
        });
        if (formatter && (!this.options.interpolation.format || this.options.interpolation.format === defOpts.interpolation.format)) {
          s2.formatter = createClassOnDemand(formatter);
          s2.formatter.init(s2, this.options);
          this.options.interpolation.format = s2.formatter.format.bind(s2.formatter);
        }
        s2.interpolator = new Interpolator(this.options);
        s2.utils = {
          hasLoadedNamespace: this.hasLoadedNamespace.bind(this)
        };
        s2.backendConnector = new Connector(createClassOnDemand(this.modules.backend), s2.resourceStore, s2, this.options);
        s2.backendConnector.on("*", function(event) {
          for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
            args[_key - 1] = arguments[_key];
          }
          _this.emit(event, ...args);
        });
        if (this.modules.languageDetector) {
          s2.languageDetector = createClassOnDemand(this.modules.languageDetector);
          if (s2.languageDetector.init)
            s2.languageDetector.init(s2, this.options.detection, this.options);
        }
        if (this.modules.i18nFormat) {
          s2.i18nFormat = createClassOnDemand(this.modules.i18nFormat);
          if (s2.i18nFormat.init)
            s2.i18nFormat.init(this);
        }
        this.translator = new Translator(this.services, this.options);
        this.translator.on("*", function(event) {
          for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
            args[_key2 - 1] = arguments[_key2];
          }
          _this.emit(event, ...args);
        });
        this.modules.external.forEach((m2) => {
          if (m2.init)
            m2.init(this);
        });
      }
      this.format = this.options.interpolation.format;
      if (!callback)
        callback = noop$1;
      if (this.options.fallbackLng && !this.services.languageDetector && !this.options.lng) {
        const codes = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
        if (codes.length > 0 && codes[0] !== "dev")
          this.options.lng = codes[0];
      }
      if (!this.services.languageDetector && !this.options.lng) {
        this.logger.warn("init: no languageDetector is used and no lng is defined");
      }
      const storeApi = ["getResource", "hasResourceBundle", "getResourceBundle", "getDataByLanguage"];
      storeApi.forEach((fcName) => {
        this[fcName] = function() {
          return _this.store[fcName](...arguments);
        };
      });
      const storeApiChained = ["addResource", "addResources", "addResourceBundle", "removeResourceBundle"];
      storeApiChained.forEach((fcName) => {
        this[fcName] = function() {
          _this.store[fcName](...arguments);
          return _this;
        };
      });
      const deferred = defer();
      const load = () => {
        const finish = (err, t2) => {
          if (this.isInitialized && !this.initializedStoreOnce)
            this.logger.warn("init: i18next is already initialized. You should call init just once!");
          this.isInitialized = true;
          if (!this.options.isClone)
            this.logger.log("initialized", this.options);
          this.emit("initialized", this.options);
          deferred.resolve(t2);
          callback(err, t2);
        };
        if (this.languages && this.options.compatibilityAPI !== "v1" && !this.isInitialized)
          return finish(null, this.t.bind(this));
        this.changeLanguage(this.options.lng, finish);
      };
      if (this.options.resources || !this.options.initImmediate) {
        load();
      } else {
        setTimeout(load, 0);
      }
      return deferred;
    }
    loadResources(language) {
      let callback = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop$1;
      let usedCallback = callback;
      const usedLng = typeof language === "string" ? language : this.language;
      if (typeof language === "function")
        usedCallback = language;
      if (!this.options.resources || this.options.partialBundledLanguages) {
        if (usedLng && usedLng.toLowerCase() === "cimode")
          return usedCallback();
        const toLoad = [];
        const append = (lng) => {
          if (!lng)
            return;
          const lngs = this.services.languageUtils.toResolveHierarchy(lng);
          lngs.forEach((l2) => {
            if (toLoad.indexOf(l2) < 0)
              toLoad.push(l2);
          });
        };
        if (!usedLng) {
          const fallbacks = this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);
          fallbacks.forEach((l2) => append(l2));
        } else {
          append(usedLng);
        }
        if (this.options.preload) {
          this.options.preload.forEach((l2) => append(l2));
        }
        this.services.backendConnector.load(toLoad, this.options.ns, (e2) => {
          if (!e2 && !this.resolvedLanguage && this.language)
            this.setResolvedLanguage(this.language);
          usedCallback(e2);
        });
      } else {
        usedCallback(null);
      }
    }
    reloadResources(lngs, ns, callback) {
      const deferred = defer();
      if (!lngs)
        lngs = this.languages;
      if (!ns)
        ns = this.options.ns;
      if (!callback)
        callback = noop$1;
      this.services.backendConnector.reload(lngs, ns, (err) => {
        deferred.resolve();
        callback(err);
      });
      return deferred;
    }
    use(module) {
      if (!module)
        throw new Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");
      if (!module.type)
        throw new Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");
      if (module.type === "backend") {
        this.modules.backend = module;
      }
      if (module.type === "logger" || module.log && module.warn && module.error) {
        this.modules.logger = module;
      }
      if (module.type === "languageDetector") {
        this.modules.languageDetector = module;
      }
      if (module.type === "i18nFormat") {
        this.modules.i18nFormat = module;
      }
      if (module.type === "postProcessor") {
        postProcessor.addPostProcessor(module);
      }
      if (module.type === "formatter") {
        this.modules.formatter = module;
      }
      if (module.type === "3rdParty") {
        this.modules.external.push(module);
      }
      return this;
    }
    setResolvedLanguage(l2) {
      if (!l2 || !this.languages)
        return;
      if (["cimode", "dev"].indexOf(l2) > -1)
        return;
      for (let li = 0; li < this.languages.length; li++) {
        const lngInLngs = this.languages[li];
        if (["cimode", "dev"].indexOf(lngInLngs) > -1)
          continue;
        if (this.store.hasLanguageSomeTranslations(lngInLngs)) {
          this.resolvedLanguage = lngInLngs;
          break;
        }
      }
    }
    changeLanguage(lng, callback) {
      var _this2 = this;
      this.isLanguageChangingTo = lng;
      const deferred = defer();
      this.emit("languageChanging", lng);
      const setLngProps = (l2) => {
        this.language = l2;
        this.languages = this.services.languageUtils.toResolveHierarchy(l2);
        this.resolvedLanguage = void 0;
        this.setResolvedLanguage(l2);
      };
      const done = (err, l2) => {
        if (l2) {
          setLngProps(l2);
          this.translator.changeLanguage(l2);
          this.isLanguageChangingTo = void 0;
          this.emit("languageChanged", l2);
          this.logger.log("languageChanged", l2);
        } else {
          this.isLanguageChangingTo = void 0;
        }
        deferred.resolve(function() {
          return _this2.t(...arguments);
        });
        if (callback)
          callback(err, function() {
            return _this2.t(...arguments);
          });
      };
      const setLng = (lngs) => {
        if (!lng && !lngs && this.services.languageDetector)
          lngs = [];
        const l2 = typeof lngs === "string" ? lngs : this.services.languageUtils.getBestMatchFromCodes(lngs);
        if (l2) {
          if (!this.language) {
            setLngProps(l2);
          }
          if (!this.translator.language)
            this.translator.changeLanguage(l2);
          if (this.services.languageDetector && this.services.languageDetector.cacheUserLanguage)
            this.services.languageDetector.cacheUserLanguage(l2);
        }
        this.loadResources(l2, (err) => {
          done(err, l2);
        });
      };
      if (!lng && this.services.languageDetector && !this.services.languageDetector.async) {
        setLng(this.services.languageDetector.detect());
      } else if (!lng && this.services.languageDetector && this.services.languageDetector.async) {
        if (this.services.languageDetector.detect.length === 0) {
          this.services.languageDetector.detect().then(setLng);
        } else {
          this.services.languageDetector.detect(setLng);
        }
      } else {
        setLng(lng);
      }
      return deferred;
    }
    getFixedT(lng, ns, keyPrefix) {
      var _this3 = this;
      const fixedT = function(key, opts) {
        let options;
        if (typeof opts !== "object") {
          for (var _len3 = arguments.length, rest = new Array(_len3 > 2 ? _len3 - 2 : 0), _key3 = 2; _key3 < _len3; _key3++) {
            rest[_key3 - 2] = arguments[_key3];
          }
          options = _this3.options.overloadTranslationOptionHandler([key, opts].concat(rest));
        } else {
          options = {
            ...opts
          };
        }
        options.lng = options.lng || fixedT.lng;
        options.lngs = options.lngs || fixedT.lngs;
        options.ns = options.ns || fixedT.ns;
        options.keyPrefix = options.keyPrefix || keyPrefix || fixedT.keyPrefix;
        const keySeparator = _this3.options.keySeparator || ".";
        let resultKey;
        if (options.keyPrefix && Array.isArray(key)) {
          resultKey = key.map((k2) => `${options.keyPrefix}${keySeparator}${k2}`);
        } else {
          resultKey = options.keyPrefix ? `${options.keyPrefix}${keySeparator}${key}` : key;
        }
        return _this3.t(resultKey, options);
      };
      if (typeof lng === "string") {
        fixedT.lng = lng;
      } else {
        fixedT.lngs = lng;
      }
      fixedT.ns = ns;
      fixedT.keyPrefix = keyPrefix;
      return fixedT;
    }
    t() {
      return this.translator && this.translator.translate(...arguments);
    }
    exists() {
      return this.translator && this.translator.exists(...arguments);
    }
    setDefaultNamespace(ns) {
      this.options.defaultNS = ns;
    }
    hasLoadedNamespace(ns) {
      let options = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
      if (!this.isInitialized) {
        this.logger.warn("hasLoadedNamespace: i18next was not initialized", this.languages);
        return false;
      }
      if (!this.languages || !this.languages.length) {
        this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty", this.languages);
        return false;
      }
      const lng = options.lng || this.resolvedLanguage || this.languages[0];
      const fallbackLng = this.options ? this.options.fallbackLng : false;
      const lastLng = this.languages[this.languages.length - 1];
      if (lng.toLowerCase() === "cimode")
        return true;
      const loadNotPending = (l2, n2) => {
        const loadState = this.services.backendConnector.state[`${l2}|${n2}`];
        return loadState === -1 || loadState === 2;
      };
      if (options.precheck) {
        const preResult = options.precheck(this, loadNotPending);
        if (preResult !== void 0)
          return preResult;
      }
      if (this.hasResourceBundle(lng, ns))
        return true;
      if (!this.services.backendConnector.backend || this.options.resources && !this.options.partialBundledLanguages)
        return true;
      if (loadNotPending(lng, ns) && (!fallbackLng || loadNotPending(lastLng, ns)))
        return true;
      return false;
    }
    loadNamespaces(ns, callback) {
      const deferred = defer();
      if (!this.options.ns) {
        if (callback)
          callback();
        return Promise.resolve();
      }
      if (typeof ns === "string")
        ns = [ns];
      ns.forEach((n2) => {
        if (this.options.ns.indexOf(n2) < 0)
          this.options.ns.push(n2);
      });
      this.loadResources((err) => {
        deferred.resolve();
        if (callback)
          callback(err);
      });
      return deferred;
    }
    loadLanguages(lngs, callback) {
      const deferred = defer();
      if (typeof lngs === "string")
        lngs = [lngs];
      const preloaded = this.options.preload || [];
      const newLngs = lngs.filter((lng) => preloaded.indexOf(lng) < 0);
      if (!newLngs.length) {
        if (callback)
          callback();
        return Promise.resolve();
      }
      this.options.preload = preloaded.concat(newLngs);
      this.loadResources((err) => {
        deferred.resolve();
        if (callback)
          callback(err);
      });
      return deferred;
    }
    dir(lng) {
      if (!lng)
        lng = this.resolvedLanguage || (this.languages && this.languages.length > 0 ? this.languages[0] : this.language);
      if (!lng)
        return "rtl";
      const rtlLngs = ["ar", "shu", "sqr", "ssh", "xaa", "yhd", "yud", "aao", "abh", "abv", "acm", "acq", "acw", "acx", "acy", "adf", "ads", "aeb", "aec", "afb", "ajp", "apc", "apd", "arb", "arq", "ars", "ary", "arz", "auz", "avl", "ayh", "ayl", "ayn", "ayp", "bbz", "pga", "he", "iw", "ps", "pbt", "pbu", "pst", "prp", "prd", "ug", "ur", "ydd", "yds", "yih", "ji", "yi", "hbo", "men", "xmn", "fa", "jpr", "peo", "pes", "prs", "dv", "sam", "ckb"];
      const languageUtils = this.services && this.services.languageUtils || new LanguageUtil(get$1());
      return rtlLngs.indexOf(languageUtils.getLanguagePartFromCode(lng)) > -1 || lng.toLowerCase().indexOf("-arab") > 1 ? "rtl" : "ltr";
    }
    static createInstance() {
      let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      let callback = arguments.length > 1 ? arguments[1] : void 0;
      return new I18n(options, callback);
    }
    cloneInstance() {
      let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
      let callback = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : noop$1;
      const forkResourceStore = options.forkResourceStore;
      if (forkResourceStore)
        delete options.forkResourceStore;
      const mergedOptions = {
        ...this.options,
        ...options,
        ...{
          isClone: true
        }
      };
      const clone = new I18n(mergedOptions);
      if (options.debug !== void 0 || options.prefix !== void 0) {
        clone.logger = clone.logger.clone(options);
      }
      const membersToCopy = ["store", "services", "language"];
      membersToCopy.forEach((m2) => {
        clone[m2] = this[m2];
      });
      clone.services = {
        ...this.services
      };
      clone.services.utils = {
        hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
      };
      if (forkResourceStore) {
        clone.store = new ResourceStore(this.store.data, mergedOptions);
        clone.services.resourceStore = clone.store;
      }
      clone.translator = new Translator(clone.services, mergedOptions);
      clone.translator.on("*", function(event) {
        for (var _len4 = arguments.length, args = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
          args[_key4 - 1] = arguments[_key4];
        }
        clone.emit(event, ...args);
      });
      clone.init(mergedOptions, callback);
      clone.translator.options = mergedOptions;
      clone.translator.backendConnector.services.utils = {
        hasLoadedNamespace: clone.hasLoadedNamespace.bind(clone)
      };
      return clone;
    }
    toJSON() {
      return {
        options: this.options,
        store: this.store,
        language: this.language,
        languages: this.languages,
        resolvedLanguage: this.resolvedLanguage
      };
    }
  }
  const instance = I18n.createInstance();
  instance.createInstance = I18n.createInstance;
  instance.createInstance;
  instance.dir;
  instance.init;
  instance.loadResources;
  instance.reloadResources;
  instance.use;
  instance.changeLanguage;
  instance.getFixedT;
  instance.t;
  instance.exists;
  instance.setDefaultNamespace;
  instance.hasLoadedNamespace;
  instance.loadNamespaces;
  instance.loadLanguages;
  var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {};
  function getDefaultExportFromCjs(x2) {
    return x2 && x2.__esModule && Object.prototype.hasOwnProperty.call(x2, "default") ? x2["default"] : x2;
  }
  function getAugmentedNamespace(n2) {
    if (n2.__esModule)
      return n2;
    var f2 = n2.default;
    if (typeof f2 == "function") {
      var a2 = function a3() {
        if (this instanceof a3) {
          return Reflect.construct(f2, arguments, this.constructor);
        }
        return f2.apply(this, arguments);
      };
      a2.prototype = f2.prototype;
    } else
      a2 = {};
    Object.defineProperty(a2, "__esModule", { value: true });
    Object.keys(n2).forEach(function(k2) {
      var d2 = Object.getOwnPropertyDescriptor(n2, k2);
      Object.defineProperty(a2, k2, d2.get ? d2 : {
        enumerable: true,
        get: function() {
          return n2[k2];
        }
      });
    });
    return a2;
  }
  const matchHtmlEntity = /&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g;
  const htmlEntities = {
    "&amp;": "&",
    "&#38;": "&",
    "&lt;": "<",
    "&#60;": "<",
    "&gt;": ">",
    "&#62;": ">",
    "&apos;": "'",
    "&#39;": "'",
    "&quot;": '"',
    "&#34;": '"',
    "&nbsp;": " ",
    "&#160;": " ",
    "&copy;": "©",
    "&#169;": "©",
    "&reg;": "®",
    "&#174;": "®",
    "&hellip;": "…",
    "&#8230;": "…",
    "&#x2F;": "/",
    "&#47;": "/"
  };
  const unescapeHtmlEntity = (m2) => htmlEntities[m2];
  const unescape$1 = (text) => text.replace(matchHtmlEntity, unescapeHtmlEntity);
  let defaultOptions$1 = {
    bindI18n: "languageChanged",
    bindI18nStore: "",
    transEmptyNodeValue: "",
    transSupportBasicHtmlNodes: true,
    transWrapTextNodes: "",
    transKeepBasicHtmlNodesFor: ["br", "strong", "i", "p"],
    useSuspense: true,
    unescape: unescape$1
  };
  function setDefaults() {
    let options = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : {};
    defaultOptions$1 = {
      ...defaultOptions$1,
      ...options
    };
  }
  const initReactI18next = {
    type: "3rdParty",
    init(instance2) {
      setDefaults(instance2.options.react);
    }
  };
  const LANG_NS_MAIN = "main";
  const LANG_NS_SYNC = "sync";
  const PERSIST_KEY_LANGUAGE_SETTING = "wle:language";
  const PERSIST_KEY_ENABLE_CUSTOM_SELECTIONS_SETTING = "wle:enable-custom-selections";
  const PERSIST_KEY_ENABLE_LOAD_ALL_PAGES_SETTING = "wle:enable-load-all-pages";
  const PERSIST_KEY_ENABLE_FIREBASE_SYNC_SETTING = "wle:enable-firebase-sync";
  const PERSIST_KEY_FIREBASE_SYNC_CONF_SETTING = "wle:firebase-sync-conf";
  const PERSIST_KEY_LAST_PAGE = "wle:last-page";
  const PERSIST_KEY_CUSTOM_SELECTIONS_ACTIVE_EXERCISE = "wle:custom-selections-active-exercise";
  const PERSIST_KEY_CUSTOM_SELECTIONS_ACTIVE_SECTIONS = "wle:custom-selections-active-sections";
  const PERSIST_KEY_CUSTOM_SELECTIONS_EXERCISES_STORAGE = "wle:custom-selections-exercises-storage";
  const PERSIST_KEY_CUSTOM_SELECTIONS_STORAGE = "wle:custom-selections-storage";
  const PERSIST_KEY_FIREBASE_UUID = "wle:firebase-uuid";
  const PERSIST_KEY_FIREBASE_CONFIG = "wle:firebase-config";
  const SETTING_LANGUAGE_RADIO_BUTTON_BASE_ID = "wle-setting-language-radio-button";
  const SETTING_LANGUAGE_RADIO_BUTTON_CHECKED_SELECTOR = "[id^='wle-setting-language-radio-button'][data-state='checked']";
  const SETTING_ENABLE_CUSTOM_SELECTIONS_ID = "wle-setting-enable-custom-selections";
  const SETTING_ENABLE_LOAD_ALL_PAGES_ID = "wle-setting-enable-load-all-pages";
  const SETTING_ENABLE_FIREBASE_SYNC_ID = "wle-setting-enable-firebase-sync";
  const SETTING_FIREBASE_SYNC_CONF_ID = "wle-setting-firebase-conf";
  const DIALOGUE_SAVE_CUSTOM_SELECTION_NAME_ID = "wle-dialogue-save-custom-selection-name";
  const ELEM_MAIN_APP_ID = "wle-main-app";
  const ELEM_PERSONAL_MENU_ITEM_WLE_SELECTION_ID = "wle-personal-menu-selection-item";
  const ELEM_PERSONAL_MENU_ITEM_WLE_SYNCHRONIZATION_ID = "wle-personal-menu-synchronization-item";
  const ELEM_BOTTOM_MENU_ITEM_WLE_SETTINGS_ID = "wle-bottom-menu-settings-item";
  const ELEM_LOGGED_IN_TOP_BAR_CONTAINER_ID = "wle-top-bar-container";
  const ELEM_LOGGED_IN_TOP_BAR_CONTAINER_ITEM_WLE_SELECTION_ID = "wle-top-bar-container-selection-item";
  const ELEM_LOGGED_IN_TOP_BAR_CONTAINER_ITEM_WLE_SYNCHRONIZATION_ID = "wle-top-bar-container-synchronization-item";
  const ELEM_LOGGED_IN_TOP_BAR_CONTAINER_ITEM_WLE_SETTINGS_ID = "wle-top-bar-container-settings-item";
  const ELEM_PAGE_EXERCISE_SECTIONS_TOOLBAR_CONTAINER_ID = "wle-page-exercise-sections-toolbar-container";
  const ELEM_PAGE_EXERCISE_SECTIONS_ADDITION_BASE_ID = "wle-page-exercise-sections-addition";
  const ELEM_PAGE_EXERCISE_EXPLORE_SECTIONS_TOOLBAR_CONTAINER_ID = "wle-page-exercise-explore-sections-toolbar-container";
  const ELEM_WL_PERSONAL_MENU_SELECTOR = "nav:not(.public).nav-default.ink-navigation > #menu";
  const ELEM_WL_BOTTOM_MENU_SELECTOR = ".public.nav-default.ink-navigation > #menu";
  const ELEM_WL_LOGGED_IN_TOP_BAR_SELECTOR = "body:not(.anyone) > #page > #topBar";
  const ELEM_WL_PAGE_EXERCISE_TITLE_SELECTOR = "h1 > a";
  const ELEM_WL_PAGE_EXERCISE_SECTIONS_CONTAINER_SELECTOR = "#content .all-100:nth-child(4)";
  const ELEM_WL_PAGE_EXERCISE_SECTION_ROWS_SELECTOR = "#content .ink-table > tbody > tr";
  const ELEM_WL_PAGE_EXERCISE_SECTION_ROW_PRACTICE_ANCHOR_SELECTOR = "[href^='/practice/'][href$='/start']";
  const ELEM_WL_PAGE_EXERCISE_SECTION_ROW_ANCHOR_SELECTOR = "h4 > a";
  const ELEM_WL_PAGE_EXERCISE_EXPLORE_SECTION_CONTAINER_SELECTOR = "div.all-100:nth-child(2) > hr:nth-child(2)";
  const ELEM_WL_PAGE_EXERCISE_EXPLORE_SECTION_LINK_FIRST_PAGE_SELECTOR = "a[href$='page=1']";
  const ELEM_WL_PAGE_EXERCISE_EXPLORE_SECTION_LINK_NEXT_PAGE_SELECTOR = ".next > a";
  const ELEM_WL_PAGE_EXERCISE_EXPLORE_SECTION_QUESTIONS_TABLE_SELECTOR = ".ink-table";
  const RE_PAGE_EXERCISE_PRACTICE_LINK = /\/practice\/([0-9]+)\/([0-9]+)\/start/;
  const VAL_PAGE_EXERCISE_EXPLORE_SECTION_MAX_ITERATIONS = 10;
  const VAL_FIREBASE_SYNC_UUID_KEY = "sync/uuid";
  const VAL_FIREBASE_SYNC_SETTINGS_KEY = "sync/settings";
  const VAL_FIREBASE_SYNC_CUSTOM_SELECTIONS_EXERCISES_STORAGE_KEY = "sync/customSelectionsExercisesStorage";
  const VAL_FIREBASE_SYNC_CUSTOM_SELECTIONS_STORAGE_KEY = "sync/customSelectionsStorage";
  const VAL_FIREBASE_SYNC_SHARED_KEY = "shared";
  var _GM_deleteValue = /* @__PURE__ */ (() => typeof GM_deleteValue != "undefined" ? GM_deleteValue : void 0)();
  var _GM_getValue = /* @__PURE__ */ (() => typeof GM_getValue != "undefined" ? GM_getValue : void 0)();
  var _GM_setValue = /* @__PURE__ */ (() => typeof GM_setValue != "undefined" ? GM_setValue : void 0)();
  class GMStorage {
    /**
     * Retrieve the stored data associated with the given key from Greasemonkey storage (GMStorage).
     *
     * @param key - The key to retrieve data from Greasemonkey storage.
     * @returns The data associated with the provided key if available, or null if the key is not found in
     * Greasemonkey storage.
     */
    static get(key) {
      const item = _GM_getValue(key, "");
      if (item) {
        try {
          return JSON.parse(item);
        } catch {
          return null;
        }
      }
      return null;
    }
    /**
     * Store the provided data associated with the given key in Greasemonkey storage (GMStorage).
     *
     * @param key - The key under which to store the data in Greasemonkey storage.
     * @param value - The data to be stored.
     */
    static set(key, value) {
      const item = JSON.stringify(value);
      _GM_setValue(key, item);
    }
    /**
     * Delete the data associated with the given key from Greasemonkey storage (GMStorage).
     *
     * @param key - The key for which to delete data from Greasemonkey storage.
     */
    static delete(key) {
      _GM_deleteValue(key);
    }
  }
  /**
   * A boolean value indicating whether Greasemonkey storage (GMStorage) is supported in the current environment.
   * It checks whether GM_getValue, GM_setValue, and GM_deleteValue are available as functions.
   */
  __publicField(GMStorage, "supported", typeof _GM_getValue === "function" && typeof _GM_setValue === "function" && typeof _GM_deleteValue === "function");
  class LocalStorage {
    /**
     * Retrieve the stored data associated with the given key from Web Storage (LocalStorage).
     *
     * @param key - The key to retrieve data from Web Storage.
     * @returns The data associated with the provided key if available, or null if the key is not found in Web Storage.
     */
    static get(key) {
      const item = localStorage.getItem(key);
      if (item) {
        try {
          return JSON.parse(item);
        } catch {
          return null;
        }
      }
      return null;
    }
    /**
     * Store the provided data associated with the given key in Web Storage (LocalStorage).
     *
     * @param key - The key under which to store the data in Web Storage.
     * @param value - The data to be stored.
     */
    static set(key, value) {
      const item = JSON.stringify(value);
      localStorage.setItem(key, item);
    }
    /**
     * Delete the data associated with the given key from Web Storage (LocalStorage).
     *
     * @param {string} key - The key for which to delete data from Web Storage.
     */
    static delete(key) {
      localStorage.removeItem(key);
    }
  }
  /**
   * A boolean value indicating whether Web Storage (LocalStorage) is supported in the current environment.
   * It checks whether localStorage is available as an object.
   */
  __publicField(LocalStorage, "supported", typeof localStorage === "object");
  let MemoryStorage$1 = (_a = class {
    /**
     * Retrieve the data associated with the provided key from MemoryStorage.
     *
     * @param key - The key for which to retrieve the data from MemoryStorage.
     * @returns The data associated with the provided key, or null if the key is not found in MemoryStorage.
     */
    static get(key) {
      const item = this.map.get(key);
      return item !== void 0 ? item : null;
    }
    /**
     * Store the provided data with the given key in MemoryStorage.
     *
     * @param key - The key under which to store the data in MemoryStorage.
     * @param value - The data to be stored.
     */
    static set(key, value) {
      this.map.set(key, value);
    }
    /**
     * Delete the data associated with the given key from MemoryStorage.
     *
     * @param key - The key for which to delete the data from MemoryStorage.
     */
    static delete(key) {
      this.map.delete(key);
    }
  }, // The Map used to store the data as key-value pairs.
  __publicField(_a, "map", /* @__PURE__ */ new Map()), // A property indicating that MemoryStorage is always supported as it doesn't rely on external mechanisms.
  __publicField(_a, "supported", true), _a);
  class ScriptStorage {
    /**
     * Retrieve the stored data associated with the given key from the supported storage options, with fallback support.
     * It first attempts to retrieve data from Greasemonkey storage (GMStorage), then falls back to Web Storage
     * (LocalStorage) if available, and finally, if neither is supported or an error occurs in both cases, it retrieves
     * data from MemoryStorage.
     *
     * @param key - The key to retrieve data from the supported storage options.
     * @returns The data associated with the provided key if available, or null if the key is not found in any of the
     * supported storage options.
     */
    static get(key) {
      if (GMStorage.supported) {
        try {
          return GMStorage.get(key);
        } catch {
        }
      }
      if (LocalStorage.supported) {
        try {
          return LocalStorage.get(key);
        } catch {
        }
      }
      return MemoryStorage$1.get(key);
    }
    /**
     * Store the provided data associated with the given key in the supported storage options, with fallback support.
     * It first attempts to store data in Greasemonkey storage (GMStorage), then falls back to Web Storage
     * (LocalStorage) if available, and finally, if neither is supported or an error occurs in both cases,
     * it stores data in MemoryStorage.
     *
     * @param key - The key under which to store data in the supported storage options.
     * @param value - The data to be stored.
     */
    static set(key, value) {
      if (GMStorage.supported) {
        try {
          return GMStorage.set(key, value);
        } catch {
        }
      }
      if (LocalStorage.supported) {
        try {
          return LocalStorage.set(key, value);
        } catch {
        }
      }
      return MemoryStorage$1.set(key, value);
    }
    /**
     * Delete the data associated with the given key from the supported storage options, with fallback support.
     * It first attempts to delete data from Greasemonkey storage (GMStorage), then falls back to Web Storage
     * (LocalStorage) if available, and finally, if neither is supported or an error occurs in both cases,
     * it deletes data from MemoryStorage.
     *
     * @param key - The key for which to delete data from the supported storage options.
     */
    static delete(key) {
      if (GMStorage.supported) {
        try {
          return GMStorage.delete(key);
        } catch {
        }
      }
      if (LocalStorage.supported) {
        try {
          return LocalStorage.delete(key);
        } catch {
        }
      }
      return MemoryStorage$1.delete(key);
    }
  }
  const title$1 = "Wordalist Enhancements";
  const shortTitle$1 = "WLE";
  const langNameEnglish$1 = "English";
  const langNameEnglishUS$1 = "English (US)";
  const langNameSwedish$1 = "Swedish";
  const langNameSwedishSE$1 = "Swedish (Sweden)";
  const menuWLESelection$1 = "WLE Selections";
  const menuWLESynchronization$1 = "WLE Sync";
  const menuWLESettings$1 = "WLE Settings";
  const settings$1 = "Settings";
  const save$1 = "Save";
  const yes$1 = "Yes";
  const no$1 = "No";
  const page$1 = "Page {{count}}";
  const lastPracticed$1 = "Last";
  const lastPracticedNever$1 = "Never";
  const practicesToday$1 = "Today";
  const practicesTotal$1 = "Total";
  const wordalistSection_one$1 = "{{count}} section";
  const wordalistSection_other$1 = "{{count}} sections";
  const wordalistExerciseInfo_one$1 = "{{count}} Wordalist exercise information value";
  const wordalistExerciseInfo_other$1 = "{{count}} Wordalist exercise information values";
  const wordalistCustomSelection_one$1 = "{{count}} custom selection";
  const wordalistCustomSelection_other$1 = "{{count}} custom selections";
  const wordalistExercise$1 = "Wordalist exercise #{{id}}";
  const actionPracticeEndNotificationTitle$1 = "Custom exercise complete";
  const actionPracticeEndNotificationText_one$1 = 'Good job on practicing "{{exercise}}", this was your first time practicing it today!';
  const actionPracticeEndNotificationText_other$1 = 'Good job on practicing "{{exercise}}", you have now practiced it {{count}} times today!';
  const settingGeneralDescription$1 = "Make changes to your WLE settings here. Click save when you're done.";
  const settingWLELanguage$1 = "Language";
  const settingActivateSelection$1 = "Activate custom sections selections";
  const settingActivateLoadAllPages$1 = "Activate load all pages functionality";
  const settingActivateFirebaseSync$1 = "Activate Firebase synchronization";
  const settingFirebaseConfiguration$1 = "Firebase configuration";
  const settingFirebaseConfigurationErrorTitle$1 = "Bad Firebase configuration";
  const settingFirebaseConfigurationErrorParseText$1 = "The Firebase configuration was not correctly entered.";
  const settingFirebaseConfigurationErrorUsageWriteText$1 = "Could not write to the Firebase database, either the configuration is wrong or the permissions are incorrect.";
  const settingFirebaseConfigurationErrorUsageReadText$1 = "Could not read from the Firebase database, either the configuration is wrong or the permissions are incorrect.";
  const settingsSaved$1 = "Settings have been saved";
  const practiceSelectionDescription$1 = "Select custom sections to practice. Similar to the 'Practice All' session, but with only the sections you have selected. It is also possible to save custom sections selections for later use.";
  const pageExercisePracticeSelectionLabel$1 = "Select section";
  const pageExercisePracticeToolbarResetButton$1 = "Reset selections";
  const pageExercisePracticeToolbarSaveButton$1 = "Save selections";
  const pageExercisePracticeToolbarSaveUpdateButton$1 = "Update custom selection";
  const pageExercisePracticeToolbarDisabledLink$1 = "Choose sections to include in a custom practice";
  const pageExercisePracticeToolbarDirectLink_one$1 = 'Practice {{count}} section from "{{exercise}}"';
  const pageExercisePracticeToolbarDirectLink_other$1 = 'Practice {{count}} sections from "{{exercise}}"';
  const pageExerciseSaveDialogueTitle$1 = "Custom selection options";
  const pageExerciseSaveDialogueGeneralDescription$1 = "Choose a name for your custom exercise below. Click save when you're done.";
  const pageExerciseSaveDialogueName$1 = "Name";
  const pageExerciseSaveDialogueErrorGeneralTitle$1 = "Error trying to save custom exercise";
  const pageExerciseSaveDialogueErrorNoNameText$1 = "Could not save custom exercise due to the name field being empty. Try again and type a name.";
  const pageExerciseExploreSectionShowAllQuestionsButton$1 = "Show all questions";
  const pageExerciseExploreSectionShowAllQuestionsButtonDisabled$1 = "Questions loaded";
  const pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsTitle$1 = "Loaded questions";
  const pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsText_one$1 = "Loaded {{count}} page with questions.";
  const pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsText_other$1 = "Loaded {{count}} pages with questions.";
  const pageExerciseExploreSectionErrorDuringQuestionLoadTitle$1 = "Loading questions failed";
  const pageExerciseExploreSectionErrorDuringQuestionLoadText$1 = "Failed to load questions, try again later.";
  const pageExerciseExploreSectionWarningDuringQuestionLoadTitle$1 = "No questions";
  const pageExerciseExploreSectionWarningDuringQuestionLoadText$1 = "No questions were found, an error may have occurred. Maybe try again later if there should be questions to load";
  const customSelectionsStorageDialogueTitle$1 = "Saved custom practices";
  const customSelectionsStorageDialogueDescription$1 = "Your saved custom practices are listed below. You may export and import exercises. You can also rearrange the exercises in the order you prefer (* please note that sorting functionality is disabled if you use a small screen).";
  const customSelectionsStorageDialogueAlertDeleteExerciseTitle$1 = "Delete exercise";
  const customSelectionsStorageDialogueAlertDeleteExerciseText$1 = 'Are you sure you want to delete "{{exercise}}" and all its custom exercises?';
  const customSelectionsStorageDialogueAlertDeleteCustomExerciseTitle$1 = "Delete custom exercise";
  const customSelectionsStorageDialogueAlertDeleteCustomExerciseText$1 = 'Are you sure you want to delete custom exercise "{{exercise}}"?';
  const customSelectionsStorageDialogueAlertDeleteSectionTitle$1 = "Delete section";
  const customSelectionsStorageDialogueAlertDeleteSectionText$1 = 'Are you sure you want to delete section "{{section}}"?';
  const customSelectionsStorageDialogueExportExercises$1 = "Export exercises";
  const customSelectionsStorageDialogueImportExercises$1 = "Import exercises";
  const customSelectionsStorageDialogueExportDescription$1 = "Click on the textarea below to copy your custom exercises to the clipboard.";
  const customSelectionsStorageDialogueImportDescription$1 = "Import exercises below by pasting the text you get when exporting.";
  const customSelectionsStorageDialogueImportSaveButton_zero$1 = "Save and import";
  const customSelectionsStorageDialogueImportSaveButton_one$1 = "Save and import {{count}} exercise";
  const customSelectionsStorageDialogueImportSaveButton_other$1 = "Save and import {{count}} exercises";
  const customSelectionsStorageDialogueExportNotificationCopyToClipboard$1 = "Copied text to clipboard";
  const customSelectionsStorageDialogueExportErrorCopyToClipboard$1 = "Text could not be copied to clipboard. Try again.";
  const customSelectionsStorageDialogueImportNotificationImported_zero$1 = "Imported no exercises";
  const customSelectionsStorageDialogueImportNotificationImported_one$1 = "Imported {{count}} exercise";
  const customSelectionsStorageDialogueImportNotificationImported_other$1 = "Imported {{count}} exercises";
  const customSelectionsStorageDialogueImportNotificationAndSkipped_zero$1 = ".";
  const customSelectionsStorageDialogueImportNotificationAndSkipped_one$1 = " and skipped {{count}} already existing exercises.";
  const customSelectionsStorageDialogueImportNotificationAndSkipped_other$1 = " and skipped {{count}} already existing exercises.";
  const customSelectionsStorageDialogueImportErrorFormat$1 = "Could not import exercises. Verify that the text is correct.";
  const en_US_main = {
    title: title$1,
    shortTitle: shortTitle$1,
    langNameEnglish: langNameEnglish$1,
    langNameEnglishUS: langNameEnglishUS$1,
    langNameSwedish: langNameSwedish$1,
    langNameSwedishSE: langNameSwedishSE$1,
    menuWLESelection: menuWLESelection$1,
    menuWLESynchronization: menuWLESynchronization$1,
    menuWLESettings: menuWLESettings$1,
    settings: settings$1,
    save: save$1,
    yes: yes$1,
    no: no$1,
    page: page$1,
    lastPracticed: lastPracticed$1,
    lastPracticedNever: lastPracticedNever$1,
    practicesToday: practicesToday$1,
    practicesTotal: practicesTotal$1,
    wordalistSection_one: wordalistSection_one$1,
    wordalistSection_other: wordalistSection_other$1,
    wordalistExerciseInfo_one: wordalistExerciseInfo_one$1,
    wordalistExerciseInfo_other: wordalistExerciseInfo_other$1,
    wordalistCustomSelection_one: wordalistCustomSelection_one$1,
    wordalistCustomSelection_other: wordalistCustomSelection_other$1,
    wordalistExercise: wordalistExercise$1,
    actionPracticeEndNotificationTitle: actionPracticeEndNotificationTitle$1,
    actionPracticeEndNotificationText_one: actionPracticeEndNotificationText_one$1,
    actionPracticeEndNotificationText_other: actionPracticeEndNotificationText_other$1,
    settingGeneralDescription: settingGeneralDescription$1,
    settingWLELanguage: settingWLELanguage$1,
    settingActivateSelection: settingActivateSelection$1,
    settingActivateLoadAllPages: settingActivateLoadAllPages$1,
    settingActivateFirebaseSync: settingActivateFirebaseSync$1,
    settingFirebaseConfiguration: settingFirebaseConfiguration$1,
    settingFirebaseConfigurationErrorTitle: settingFirebaseConfigurationErrorTitle$1,
    settingFirebaseConfigurationErrorParseText: settingFirebaseConfigurationErrorParseText$1,
    settingFirebaseConfigurationErrorUsageWriteText: settingFirebaseConfigurationErrorUsageWriteText$1,
    settingFirebaseConfigurationErrorUsageReadText: settingFirebaseConfigurationErrorUsageReadText$1,
    settingsSaved: settingsSaved$1,
    practiceSelectionDescription: practiceSelectionDescription$1,
    pageExercisePracticeSelectionLabel: pageExercisePracticeSelectionLabel$1,
    pageExercisePracticeToolbarResetButton: pageExercisePracticeToolbarResetButton$1,
    pageExercisePracticeToolbarSaveButton: pageExercisePracticeToolbarSaveButton$1,
    pageExercisePracticeToolbarSaveUpdateButton: pageExercisePracticeToolbarSaveUpdateButton$1,
    pageExercisePracticeToolbarDisabledLink: pageExercisePracticeToolbarDisabledLink$1,
    pageExercisePracticeToolbarDirectLink_one: pageExercisePracticeToolbarDirectLink_one$1,
    pageExercisePracticeToolbarDirectLink_other: pageExercisePracticeToolbarDirectLink_other$1,
    pageExerciseSaveDialogueTitle: pageExerciseSaveDialogueTitle$1,
    pageExerciseSaveDialogueGeneralDescription: pageExerciseSaveDialogueGeneralDescription$1,
    pageExerciseSaveDialogueName: pageExerciseSaveDialogueName$1,
    pageExerciseSaveDialogueErrorGeneralTitle: pageExerciseSaveDialogueErrorGeneralTitle$1,
    pageExerciseSaveDialogueErrorNoNameText: pageExerciseSaveDialogueErrorNoNameText$1,
    pageExerciseExploreSectionShowAllQuestionsButton: pageExerciseExploreSectionShowAllQuestionsButton$1,
    pageExerciseExploreSectionShowAllQuestionsButtonDisabled: pageExerciseExploreSectionShowAllQuestionsButtonDisabled$1,
    pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsTitle: pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsTitle$1,
    pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsText_one: pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsText_one$1,
    pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsText_other: pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsText_other$1,
    pageExerciseExploreSectionErrorDuringQuestionLoadTitle: pageExerciseExploreSectionErrorDuringQuestionLoadTitle$1,
    pageExerciseExploreSectionErrorDuringQuestionLoadText: pageExerciseExploreSectionErrorDuringQuestionLoadText$1,
    pageExerciseExploreSectionWarningDuringQuestionLoadTitle: pageExerciseExploreSectionWarningDuringQuestionLoadTitle$1,
    pageExerciseExploreSectionWarningDuringQuestionLoadText: pageExerciseExploreSectionWarningDuringQuestionLoadText$1,
    customSelectionsStorageDialogueTitle: customSelectionsStorageDialogueTitle$1,
    customSelectionsStorageDialogueDescription: customSelectionsStorageDialogueDescription$1,
    customSelectionsStorageDialogueAlertDeleteExerciseTitle: customSelectionsStorageDialogueAlertDeleteExerciseTitle$1,
    customSelectionsStorageDialogueAlertDeleteExerciseText: customSelectionsStorageDialogueAlertDeleteExerciseText$1,
    customSelectionsStorageDialogueAlertDeleteCustomExerciseTitle: customSelectionsStorageDialogueAlertDeleteCustomExerciseTitle$1,
    customSelectionsStorageDialogueAlertDeleteCustomExerciseText: customSelectionsStorageDialogueAlertDeleteCustomExerciseText$1,
    customSelectionsStorageDialogueAlertDeleteSectionTitle: customSelectionsStorageDialogueAlertDeleteSectionTitle$1,
    customSelectionsStorageDialogueAlertDeleteSectionText: customSelectionsStorageDialogueAlertDeleteSectionText$1,
    customSelectionsStorageDialogueExportExercises: customSelectionsStorageDialogueExportExercises$1,
    customSelectionsStorageDialogueImportExercises: customSelectionsStorageDialogueImportExercises$1,
    customSelectionsStorageDialogueExportDescription: customSelectionsStorageDialogueExportDescription$1,
    customSelectionsStorageDialogueImportDescription: customSelectionsStorageDialogueImportDescription$1,
    customSelectionsStorageDialogueImportSaveButton_zero: customSelectionsStorageDialogueImportSaveButton_zero$1,
    customSelectionsStorageDialogueImportSaveButton_one: customSelectionsStorageDialogueImportSaveButton_one$1,
    customSelectionsStorageDialogueImportSaveButton_other: customSelectionsStorageDialogueImportSaveButton_other$1,
    customSelectionsStorageDialogueExportNotificationCopyToClipboard: customSelectionsStorageDialogueExportNotificationCopyToClipboard$1,
    customSelectionsStorageDialogueExportErrorCopyToClipboard: customSelectionsStorageDialogueExportErrorCopyToClipboard$1,
    customSelectionsStorageDialogueImportNotificationImported_zero: customSelectionsStorageDialogueImportNotificationImported_zero$1,
    customSelectionsStorageDialogueImportNotificationImported_one: customSelectionsStorageDialogueImportNotificationImported_one$1,
    customSelectionsStorageDialogueImportNotificationImported_other: customSelectionsStorageDialogueImportNotificationImported_other$1,
    customSelectionsStorageDialogueImportNotificationAndSkipped_zero: customSelectionsStorageDialogueImportNotificationAndSkipped_zero$1,
    customSelectionsStorageDialogueImportNotificationAndSkipped_one: customSelectionsStorageDialogueImportNotificationAndSkipped_one$1,
    customSelectionsStorageDialogueImportNotificationAndSkipped_other: customSelectionsStorageDialogueImportNotificationAndSkipped_other$1,
    customSelectionsStorageDialogueImportErrorFormat: customSelectionsStorageDialogueImportErrorFormat$1
  };
  const title = "Wordalist Enhancements";
  const shortTitle = "WLE";
  const langNameEnglish = "Engelska";
  const langNameEnglishUS = "Engelska (USA)";
  const langNameSwedish = "Svenska";
  const langNameSwedishSE = "Svenska (Sverige)";
  const menuWLESelection = "WLE Skräddarsytt";
  const menuWLESynchronization = "WLE Synk";
  const menuWLESettings = "WLE Inställningar";
  const settings = "Inställningar";
  const save = "Spara";
  const yes = "Ja";
  const no = "Nej";
  const page = "Sida {{count}}";
  const lastPracticed = "Senaste";
  const lastPracticedNever = "Aldrig";
  const practicesToday = "Idag";
  const practicesTotal = "Totalt";
  const wordalistSection_one = "{{count}} delövning";
  const wordalistSection_other = "{{count}} delövningar";
  const wordalistExerciseInfo_one = "{{count}} wordalistövniningsinformationsvärde";
  const wordalistExerciseInfo_other = "{{count}} wordalistövniningsinformationsvärden";
  const wordalistCustomSelection_one = "{{count}} skräddarsydd övning";
  const wordalistCustomSelection_other = "{{count}} skräddarsydda övningar";
  const wordalistExercise = "Wordalistövning #{{id}}";
  const actionPracticeEndNotificationTitle = "Skräddarsydd övning klar";
  const actionPracticeEndNotificationText_one = 'Bra jobbat på övning "{{exercise}}", detta var första gången du övade på den idag!';
  const actionPracticeEndNotificationText_other = 'Bra jobbat på övning "{{exercise}}", du har nu övat {{count}} på den idag!';
  const settingGeneralDescription = "Ändra dina val för WLE-inställningar här. Tryck på spara när du är klar.";
  const settingWLELanguage = "Språk";
  const settingActivateSelection = "Aktivera skräddarsydda delövningar";
  const settingActivateLoadAllPages = "Aktivera funktionalitet för att läsa in alla sidor";
  const settingActivateFirebaseSync = "Aktivera Firebase-synkronisering";
  const settingFirebaseConfiguration = "Firebasekonfiguration";
  const settingFirebaseConfigurationErrorTitle = "Felaktik Firebasekonfiguration";
  const settingFirebaseConfigurationErrorParseText = "Firebasekonfigurationens format var felaktigt.";
  const settingFirebaseConfigurationErrorUsageWriteText = "Kunde inte skriva till Firebasedatabasen, antingen är konfigurationen fel eller så är rättigheter för databasen felaktiga.";
  const settingFirebaseConfigurationErrorUsageReadText = "Kunde inte läsa från Firebasedatabasen, antingen är konfigurationen fel eller så är rättigheter för databasen felaktiga.";
  const settingsSaved = "Inställningarna har sparats";
  const practiceSelectionDescription = "Välj skräddarsydda delövningar att öva på. Likt en 'Practice All'-övning, men där enbart de delövningar du valt finns med. Det är även möjligt att spara valen av delövningar till senare.";
  const pageExercisePracticeSelectionLabel = "Välj delövning";
  const pageExercisePracticeToolbarResetButton = "Nollställ val";
  const pageExercisePracticeToolbarSaveButton = "Spara val";
  const pageExercisePracticeToolbarSaveUpdateButton = "Uppdatera skräddarsydd övning";
  const pageExercisePracticeToolbarDisabledLink = "Välj delövningar att inkludera i en skräddarsydd övning";
  const pageExercisePracticeToolbarDirectLink_one = 'Öva på {{count}} delövning från "{{exercise}}"';
  const pageExercisePracticeToolbarDirectLink_other = 'Öva på {{count}} delövningar från "{{exercise}}"';
  const pageExerciseSaveDialogueTitle = "Val för skräddarsydda delövningar";
  const pageExerciseSaveDialogueGeneralDescription = "Välj ett namn för din skräddarsydda övning nedan. Tryck på spara när du är klar.";
  const pageExerciseSaveDialogueName = "Namn";
  const pageExerciseSaveDialogueErrorGeneralTitle = "Fel vid försök att spara skräddarsydd övning";
  const pageExerciseSaveDialogueErrorNoNameText = "Kunde inte spara den skräddarsydda övningen eftersom namn ej var angivet. Försök igen och ange ett namn.";
  const pageExerciseExploreSectionShowAllQuestionsButton = "Visa alla frågor";
  const pageExerciseExploreSectionShowAllQuestionsButtonDisabled = "Frågor är inlästa";
  const pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsTitle = "Läste in frågor";
  const pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsText_one = "Läste in {{count}} sida med frågor.";
  const pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsText_other = "Läste in {{count}} sidor med frågor.";
  const pageExerciseExploreSectionErrorDuringQuestionLoadTitle = "Inläsning misslyckades";
  const pageExerciseExploreSectionErrorDuringQuestionLoadText = "Inläsning av frågor misslyckades, försök igen senare.";
  const pageExerciseExploreSectionWarningDuringQuestionLoadTitle = "Inga frågor";
  const pageExerciseExploreSectionWarningDuringQuestionLoadText = "Inga frågor hittades, ett fel kan ha inträffat. Försöka kanske senare om det ska finnas frågor att läsa in.";
  const customSelectionsStorageDialogueTitle = "Sparade skräddarsydda övningar";
  const customSelectionsStorageDialogueDescription = "Dina sparade skräddarsydda övningar finns nedan. Du kan exportera och importera övningar. Du kan även sortera övningarna i den ordning du föredrar (* notera att sorteringsfunktionalitet är inaktiverad om du använder en liten skärm).";
  const customSelectionsStorageDialogueAlertDeleteExerciseTitle = "Ta bort övning";
  const customSelectionsStorageDialogueAlertDeleteExerciseText = 'Är du säker på att du vill ta bort "{{exercise}}" och alla dess skräddarsydda övningar?';
  const customSelectionsStorageDialogueAlertDeleteCustomExerciseTitle = "Ta bort skräddarsydd övning";
  const customSelectionsStorageDialogueAlertDeleteCustomExerciseText = 'Är du säker på att du vill ta bort den skräddarsydda övningen "{{exercise}}"?';
  const customSelectionsStorageDialogueAlertDeleteSectionTitle = "Ta bort delövning";
  const customSelectionsStorageDialogueAlertDeleteSectionText = 'Är du säker på att du vill ta bort delövning "{{section}}"?';
  const customSelectionsStorageDialogueExportExercises = "Exportera övningar";
  const customSelectionsStorageDialogueImportExercises = "Importera övningar";
  const customSelectionsStorageDialogueExportDescription = "Tryck på textfälted nedan för att kopiera dina skräddarsydda övningar till urklipp.";
  const customSelectionsStorageDialogueImportDescription = "Importera övningar nedan genom att klistra in den text du får när du exporterar.";
  const customSelectionsStorageDialogueImportSaveButton_zero = "Spara och importera";
  const customSelectionsStorageDialogueImportSaveButton_one = "Spara och importera {{count}} övning";
  const customSelectionsStorageDialogueImportSaveButton_other = "Spara och importera {{count}} övningar";
  const customSelectionsStorageDialogueExportNotificationCopyToClipboard = "Kopierade text till urklipp";
  const customSelectionsStorageDialogueExportErrorCopyToClipboard = "Text kunde inte kopieras till urklipp. Försök igen.";
  const customSelectionsStorageDialogueImportNotificationImported_zero = "Importerade inte några övningar";
  const customSelectionsStorageDialogueImportNotificationImported_one = "Importerade {{count}} övning";
  const customSelectionsStorageDialogueImportNotificationImported_other = "Importerade {{count}} övningar";
  const customSelectionsStorageDialogueImportNotificationAndSkipped_zero = ".";
  const customSelectionsStorageDialogueImportNotificationAndSkipped_one = " och skippade {{count}} redan existerande övning.";
  const customSelectionsStorageDialogueImportNotificationAndSkipped_other = " och skippade {{count}} redan existerande övningar.";
  const customSelectionsStorageDialogueImportErrorFormat = "Kunde inte importera övningar. Verifiera att texten är korrekt.";
  const sv_SE_main = {
    title,
    shortTitle,
    langNameEnglish,
    langNameEnglishUS,
    langNameSwedish,
    langNameSwedishSE,
    menuWLESelection,
    menuWLESynchronization,
    menuWLESettings,
    settings,
    save,
    yes,
    no,
    page,
    lastPracticed,
    lastPracticedNever,
    practicesToday,
    practicesTotal,
    wordalistSection_one,
    wordalistSection_other,
    wordalistExerciseInfo_one,
    wordalistExerciseInfo_other,
    wordalistCustomSelection_one,
    wordalistCustomSelection_other,
    wordalistExercise,
    actionPracticeEndNotificationTitle,
    actionPracticeEndNotificationText_one,
    actionPracticeEndNotificationText_other,
    settingGeneralDescription,
    settingWLELanguage,
    settingActivateSelection,
    settingActivateLoadAllPages,
    settingActivateFirebaseSync,
    settingFirebaseConfiguration,
    settingFirebaseConfigurationErrorTitle,
    settingFirebaseConfigurationErrorParseText,
    settingFirebaseConfigurationErrorUsageWriteText,
    settingFirebaseConfigurationErrorUsageReadText,
    settingsSaved,
    practiceSelectionDescription,
    pageExercisePracticeSelectionLabel,
    pageExercisePracticeToolbarResetButton,
    pageExercisePracticeToolbarSaveButton,
    pageExercisePracticeToolbarSaveUpdateButton,
    pageExercisePracticeToolbarDisabledLink,
    pageExercisePracticeToolbarDirectLink_one,
    pageExercisePracticeToolbarDirectLink_other,
    pageExerciseSaveDialogueTitle,
    pageExerciseSaveDialogueGeneralDescription,
    pageExerciseSaveDialogueName,
    pageExerciseSaveDialogueErrorGeneralTitle,
    pageExerciseSaveDialogueErrorNoNameText,
    pageExerciseExploreSectionShowAllQuestionsButton,
    pageExerciseExploreSectionShowAllQuestionsButtonDisabled,
    pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsTitle,
    pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsText_one,
    pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsText_other,
    pageExerciseExploreSectionErrorDuringQuestionLoadTitle,
    pageExerciseExploreSectionErrorDuringQuestionLoadText,
    pageExerciseExploreSectionWarningDuringQuestionLoadTitle,
    pageExerciseExploreSectionWarningDuringQuestionLoadText,
    customSelectionsStorageDialogueTitle,
    customSelectionsStorageDialogueDescription,
    customSelectionsStorageDialogueAlertDeleteExerciseTitle,
    customSelectionsStorageDialogueAlertDeleteExerciseText,
    customSelectionsStorageDialogueAlertDeleteCustomExerciseTitle,
    customSelectionsStorageDialogueAlertDeleteCustomExerciseText,
    customSelectionsStorageDialogueAlertDeleteSectionTitle,
    customSelectionsStorageDialogueAlertDeleteSectionText,
    customSelectionsStorageDialogueExportExercises,
    customSelectionsStorageDialogueImportExercises,
    customSelectionsStorageDialogueExportDescription,
    customSelectionsStorageDialogueImportDescription,
    customSelectionsStorageDialogueImportSaveButton_zero,
    customSelectionsStorageDialogueImportSaveButton_one,
    customSelectionsStorageDialogueImportSaveButton_other,
    customSelectionsStorageDialogueExportNotificationCopyToClipboard,
    customSelectionsStorageDialogueExportErrorCopyToClipboard,
    customSelectionsStorageDialogueImportNotificationImported_zero,
    customSelectionsStorageDialogueImportNotificationImported_one,
    customSelectionsStorageDialogueImportNotificationImported_other,
    customSelectionsStorageDialogueImportNotificationAndSkipped_zero,
    customSelectionsStorageDialogueImportNotificationAndSkipped_one,
    customSelectionsStorageDialogueImportNotificationAndSkipped_other,
    customSelectionsStorageDialogueImportErrorFormat
  };
  const dialogueGeneralDescription$1 = "Use synchronized storage to save or retrieve different settings or states here.";
  const dialogueSectionSettingsLanguageTitle$1 = "WLE Settings: Language";
  const dialogueSectionSelectionsExercisesTitle$1 = "WLE Selections: Wordalist Exercises Info";
  const dialogueSectionSelectionsCustomSelectionsTitle$1 = "WLE Selections: Custom Selections";
  const dialogueSectionSettingsLanguageLocal$1 = "Local language";
  const dialogueSectionSettingsLanguageSync$1 = "Language in sync";
  const dialogueSectionSelectionsExercisesLocal$1 = "Local Wordalist exercises info";
  const dialogueSectionSelectionsExercisesSync$1 = "Wordalist exercises info in sync";
  const dialogueSectionSelectionsCustomSelectionsLocal$1 = "Local custom selections";
  const dialogueSectionSelectionsCustomSelectionsSync$1 = "Custom selections in sync";
  const alertUploadTitle$1 = "Replace value in sync";
  const alertDownloadTitle$1 = "Replace local value";
  const alertUploadText$1 = "Are you sure you want to replace the current synchronized value with {{value}}?";
  const alertDownloadText$1 = "Are you sure you want to replace the current local value with {{value}}?";
  const en_US_sync = {
    dialogueGeneralDescription: dialogueGeneralDescription$1,
    dialogueSectionSettingsLanguageTitle: dialogueSectionSettingsLanguageTitle$1,
    dialogueSectionSelectionsExercisesTitle: dialogueSectionSelectionsExercisesTitle$1,
    dialogueSectionSelectionsCustomSelectionsTitle: dialogueSectionSelectionsCustomSelectionsTitle$1,
    dialogueSectionSettingsLanguageLocal: dialogueSectionSettingsLanguageLocal$1,
    dialogueSectionSettingsLanguageSync: dialogueSectionSettingsLanguageSync$1,
    dialogueSectionSelectionsExercisesLocal: dialogueSectionSelectionsExercisesLocal$1,
    dialogueSectionSelectionsExercisesSync: dialogueSectionSelectionsExercisesSync$1,
    dialogueSectionSelectionsCustomSelectionsLocal: dialogueSectionSelectionsCustomSelectionsLocal$1,
    dialogueSectionSelectionsCustomSelectionsSync: dialogueSectionSelectionsCustomSelectionsSync$1,
    alertUploadTitle: alertUploadTitle$1,
    alertDownloadTitle: alertDownloadTitle$1,
    alertUploadText: alertUploadText$1,
    alertDownloadText: alertDownloadText$1
  };
  const dialogueGeneralDescription = "Använd det synkroniserade lagringsutrymmet för att spara eller hämta olika inställningar eller tillståndsvariabler här.";
  const dialogueSectionSettingsLanguageTitle = "WLE Inställningar: Språk";
  const dialogueSectionSelectionsExercisesTitle = "WLE Skräddarsytt: Info för wordalistövningar";
  const dialogueSectionSelectionsCustomSelectionsTitle = "WLE Skräddarsytt: Skräddarsydda övningar";
  const dialogueSectionSettingsLanguageLocal = "Lokalt språk";
  const dialogueSectionSettingsLanguageSync = "Synkat språk";
  const dialogueSectionSelectionsExercisesLocal = "Lokal info för wordalistövningar";
  const dialogueSectionSelectionsExercisesSync = "Synkad info för wordalistövningar";
  const dialogueSectionSelectionsCustomSelectionsLocal = "Lokala skräddarsydda övningar";
  const dialogueSectionSelectionsCustomSelectionsSync = "Synkade skräddarsydda övningar";
  const alertUploadTitle = "Ersätt synkroniserat värde";
  const alertDownloadTitle = "Ersätt lokalt värde";
  const alertUploadText = "Är du säker på att du vill ersätta det nuvarande synkroniserade värdet med {{value}}?";
  const alertDownloadText = "Är du säker på att du vill ersätta det nuvarande lokala värdet med {{value}}?";
  const sv_SE_sync = {
    dialogueGeneralDescription,
    dialogueSectionSettingsLanguageTitle,
    dialogueSectionSelectionsExercisesTitle,
    dialogueSectionSelectionsCustomSelectionsTitle,
    dialogueSectionSettingsLanguageLocal,
    dialogueSectionSettingsLanguageSync,
    dialogueSectionSelectionsExercisesLocal,
    dialogueSectionSelectionsExercisesSync,
    dialogueSectionSelectionsCustomSelectionsLocal,
    dialogueSectionSelectionsCustomSelectionsSync,
    alertUploadTitle,
    alertDownloadTitle,
    alertUploadText,
    alertDownloadText
  };
  const AvailableLocales = ["en", "en-US", "sv", "sv-SE"];
  const LanguageConf = {
    EN: {
      name: "English",
      i18nNameKey: "langNameEnglish",
      code: "en",
      resource: {
        main: en_US_main,
        sync: en_US_sync
      }
    },
    EN_US: {
      name: "English (US)",
      i18nNameKey: "langNameEnglishUS",
      code: "en-US",
      resource: {
        main: en_US_main,
        sync: en_US_sync
      }
    },
    SV: {
      name: "Swedish",
      i18nNameKey: "langNameSwedish",
      code: "sv",
      resource: {
        main: sv_SE_main,
        sync: sv_SE_sync
      }
    },
    SV_SE: {
      name: "Swedish (Sweden)",
      i18nNameKey: "langNameSwedishSE",
      code: "sv-SE",
      resource: {
        main: sv_SE_main,
        sync: sv_SE_sync
      }
    }
  };
  function getLanguageConfByCode(code, {
    case_insensitive = false
  } = {}) {
    for (const key in LanguageConf) {
      if (case_insensitive && LanguageConf[key].code.toLowerCase() === code.toLowerCase()) {
        return LanguageConf[key];
      } else if (!case_insensitive && LanguageConf[key].code === code) {
        return LanguageConf[key];
      }
    }
    return null;
  }
  function selectByBrowserPreferredLanguageConf() {
    let preferredLanguages = [];
    if (typeof navigator !== "undefined") {
      if (typeof navigator.languages === "object") {
        preferredLanguages = [...navigator.languages];
      } else if (typeof navigator.language === "string") {
        preferredLanguages = [navigator.language];
      }
    }
    for (const preferredLanguage of preferredLanguages) {
      const preferredLanguageCode = getLanguageConfByCode(preferredLanguage, {
        case_insensitive: true
      });
      if (preferredLanguageCode !== null) {
        return preferredLanguageCode;
      }
    }
    return null;
  }
  function getActiveLanguage() {
    const savedLanguage = ScriptStorage.get(PERSIST_KEY_LANGUAGE_SETTING);
    if (savedLanguage && getLanguageConfByCode(savedLanguage)) {
      return savedLanguage;
    }
    const preferredLanguageConf = selectByBrowserPreferredLanguageConf();
    if (preferredLanguageConf) {
      return preferredLanguageConf.code;
    }
    return LanguageConf.EN_US.code;
  }
  const defaultNS = LanguageConf.EN_US.code;
  const resources = Object.keys(LanguageConf).reduce((acc, key) => {
    acc[LanguageConf[key].code] = {
      main: LanguageConf[key].resource.main,
      sync: LanguageConf[key].resource.sync
    };
    return acc;
  }, {});
  instance.use(initReactI18next).init({
    fallbackLng: LanguageConf.EN_US.code,
    lng: getActiveLanguage(),
    resources,
    defaultNS,
    interpolation: {
      escapeValue: false
    }
  });
  instance.on("languageChanged", (newLanguage) => {
    ScriptStorage.set(PERSIST_KEY_LANGUAGE_SETTING, newLanguage);
  });
  const placeHolderValue$1 = {
    open: false,
    options: {
      language: getActiveLanguage(),
      enableCustomSelection: false,
      enableLoadAllPages: false,
      enableFirebaseSync: false,
      firebaseConfig: null
    },
    setOpen: () => {
      console.log(`SettingsContext.setOpen() placeholder function executed. This should be replaced by a new function.`);
    },
    setClosed: () => {
      console.log(`SettingsContext.setClosed() placeholder function executed. This should be replaced by a new function.`);
    },
    setOptions: ({
      language,
      enableCustomSelection,
      enableLoadAllPages,
      enableFirebaseSync,
      firebaseConfig
    }) => {
      console.log(`SettingsContext.setOptions() placeholder function executed. This should be replaced by a new function.`);
      console.log(` - language: ${language}`);
      console.log(` - enableCustomSelection: ${enableCustomSelection}`);
      console.log(` - enableLoadAllPages: ${enableLoadAllPages}`);
      console.log(` - enableFirebaseSync: ${enableFirebaseSync}`);
      console.log(` - firebaseConfig: ${firebaseConfig}`);
    }
  };
  const SettingsContext = G$1(placeHolderValue$1);
  const placeHolderValue = {
    selectedExercise: {
      exerciseID: "",
      exerciseTitle: ""
    },
    selectedSectionIterator: 0,
    selectedSections: [],
    selectionHash: "",
    selectionStorageMatch: null,
    dialogueSaveSelectionsOpen: false,
    dialogueCustomSelectionsStorageOpen: false,
    customSelectionsExercisesStorage: [],
    customSelectionsStorage: [],
    /* Save Selections Dialogue */
    setDialogueSaveSelectionsOpen: () => {
      console.log("SectionSelectionContext.setDialogueSaveSelectionsOpen() placeholder function executed. This should be replaced by a new function.");
    },
    setDialogueSaveSelectionsClosed: () => {
      console.log("SectionSelectionContext.setDialogueSaveSelectionsClosed() placeholder function executed. This should be replaced by a new function.");
    },
    /* Selections Storage */
    setDialogueCustomSelectionsStorageOpen: () => {
      console.log("SectionSelectionContext.setDialogueCustomSelectionsStorageOpen() placeholder function executed. This should be replaced by a new function.");
    },
    setDialogueCustomSelectionsStorageClosed: () => {
      console.log("SectionSelectionContext.setDialogueCustomSelectionsStorageClosed() placeholder function executed. This should be replaced by a new function.");
    },
    setInCustomSelectionsExercisesStorage: ({
      index: index2 = null,
      exerciseID,
      exerciseTitle
    }) => {
      console.log("SectionSelectionContext.setInCustomSelectionsExercisesStorage() placeholder function executed. This should be replaced by a new function.");
      console.log(` - index: ${index2}`);
      console.log(` - exerciseID: ${exerciseID}`);
      console.log(` - exerciseTitle: ${exerciseTitle}`);
    },
    setMultipleInCustomSelectionsExercisesStorage: ({
      customSelectionsExercisesStorageSetters,
      resetStorage
    }) => {
      console.log("SectionSelectionContext.setMultipleInCustomSelectionsExercisesStorage() placeholder function executed. This should be replaced by a new function.");
      console.log(`resetStorage: ${resetStorage}`);
      customSelectionsExercisesStorageSetters.forEach(({
        index: index2,
        exerciseID,
        exerciseTitle
      }, forEachIndex) => {
        console.log(`${forEachIndex} - index: ${index2}`);
        console.log(`${forEachIndex} - exerciseID: ${exerciseID}`);
        console.log(`${forEachIndex} - exerciseTitle: ${exerciseTitle}`);
      });
    },
    deleteFromCustomSelectionsExercisesStorage: ({
      exerciseID
    }) => {
      console.log("SectionSelectionContext.deleteCustomSelectionsExercisesStorage() placeholder function executed. This should be replaced by a new function.");
      console.log(` - exerciseID: ${exerciseID}`);
    },
    setInCustomSelectionsStorage: ({
      index: index2,
      name: name2,
      exerciseID,
      exerciseTitle,
      sections
    }) => {
      console.log("SectionSelectionContext.setInCustomSelectionsStorage() placeholder function executed. This should be replaced by a new function.");
      console.log(` - index: ${index2}`);
      console.log(` - name: ${name2}`);
      console.log(` - exerciseID: ${exerciseID}`);
      console.log(` - exerciseTitle: ${exerciseTitle}`);
      console.log(` - sections: ${sections}`);
    },
    setMultipleInCustomSelectionsStorage: ({
      customSelectionsStorageSetters,
      resetStorage
    }) => {
      console.log("SectionSelectionContext.setMultipleInCustomSelectionsStorage() placeholder function executed. This should be replaced by a new function.");
      console.log(`resetStorage: ${resetStorage}`);
      customSelectionsStorageSetters.forEach(({
        exerciseID,
        exerciseTitle,
        sections,
        name: name2,
        index: index2
      }, forEachIndex) => {
        console.log(`${forEachIndex} - index: ${index2}`);
        console.log(`${forEachIndex} - name: ${name2}`);
        console.log(`${forEachIndex} - exerciseID: ${exerciseID}`);
        console.log(`${forEachIndex} - exerciseTitle: ${exerciseTitle}`);
        console.log(`${forEachIndex} - sections: ${sections}`);
      });
    },
    deleteFromCustomSelectionsStorage: ({
      hash
    }) => {
      console.log("SectionSelectionContext.deleteFromCustomSelectionsStorage() placeholder function executed. This should be replaced by a new function.");
      console.log(` - hash: ${hash}`);
    },
    setInCustomSelectionSectionsStorage: ({
      hash,
      index: index2,
      sectionID,
      sectionTitle
    }) => {
      console.log("SectionSelectionContext.setInCustomSelectionSectionsStorage() placeholder function executed. This should be replaced by a new function.");
      console.log(` - hash: ${hash}`);
      console.log(` - index: ${index2}`);
      console.log(` - sectionID: ${sectionID}`);
      console.log(` - sectionTitle: ${sectionTitle}`);
    },
    setMultipleInCustomSelectionSectionsStorage: (customSelectionsSectionStorageSetters) => {
      console.log("SectionSelectionContext.setMultipleInCustomSelectionSectionsStorage() placeholder function executed. This should be replaced by a new function.");
      customSelectionsSectionStorageSetters.forEach(({
        hash,
        index: index2,
        sectionID,
        sectionTitle
      }, forEachIndex) => {
        console.log(`${forEachIndex} - hash: ${hash}`);
        console.log(`${forEachIndex} - index: ${index2}`);
        console.log(`${forEachIndex} - sectionID: ${sectionID}`);
        console.log(`${forEachIndex} - sectionTitle: ${sectionTitle}`);
      });
    },
    deleteFromCustomSelectionSectionsStorage: ({
      hash,
      sectionID
    }) => {
      console.log("SectionSelectionContext.deleteFromCustomSelectionSectionsStorage() placeholder function executed. This should be replaced by a new function.");
      console.log(` - hash: ${hash}`);
      console.log(` - sectionID: ${sectionID}`);
    },
    updateLastPracticedInCustomSelectionsStorage: ({
      hash
    }) => {
      console.log("SectionSelectionContext.updateLastPracticedInCustomSelectionsStorage() placeholder function executed. This should be replaced by a new function.");
      console.log(` - index: ${hash}`);
    },
    getCustomSelectionsStatistics: ({
      hash
    }) => {
      console.log("SectionSelectionContext.getCustomSelectionsStatistics() placeholder function executed. This should be replaced by a new function.");
      console.log(` - index: ${hash}`);
      return {
        lastPracticed: "Placeholder",
        practicesTotal: -1,
        practicesToday: -1
      };
    },
    /* Selections */
    reset: () => {
      console.log("SectionSelectionContext.reset() placeholder function executed. This should be replaced by a new function.");
    },
    resetAndAddToSelectedSections: ({
      elementID,
      sectionID
    }) => {
      console.log("SectionSelectionContext.resetAndAddToSelectedSections() placeholder function executed. This should be replaced by a new function.");
      console.log(` - elementID: ${elementID}`);
      console.log(` - sectionID: ${sectionID}`);
    },
    setSelectedExercise: ({
      exerciseID,
      exerciseTitle
    }) => {
      console.log("SectionSelectionContext.setSelectedExercise() placeholder function executed. This should be replaced by a new function.");
      console.log(` - sectionID: ${exerciseID}`);
      console.log(` - sectionID: ${exerciseTitle}`);
    },
    addToSelectedSections: ({
      elementID,
      sectionID,
      sectionTitle
    }) => {
      console.log("SettingsContext.addToSelectedSections() placeholder function executed. This should be replaced by a new function.");
      console.log(` - elementID: ${elementID}`);
      console.log(` - sectionID: ${sectionID}`);
      console.log(` - sectionTitle: ${sectionTitle}`);
    },
    setMultipleSelectedSections: (customSelectionSectionAdditions) => {
      console.log("SettingsContext.addToSelectedSections() placeholder function executed. This should be replaced by a new function.");
      customSelectionSectionAdditions.forEach(({
        elementID,
        sectionID,
        sectionTitle
      }, forEachIndex) => {
        console.log(`${forEachIndex} - elementID: ${elementID}`);
        console.log(`${forEachIndex} - sectionID: ${sectionID}`);
        console.log(`${forEachIndex} - sectionTitle: ${sectionTitle}`);
      });
    },
    removeFromSelectedSections: ({
      elementID
    }) => {
      console.log("SettingsContext.removeFromSelectedSections() placeholder function executed. This should be replaced by a new function.");
      console.log(` - elementID: ${elementID}`);
    }
  };
  const SectionSelectionContext = G$1(placeHolderValue);
  function prepareExercisePageToolbar() {
    const exerciseSectionsContainer = document.querySelector(ELEM_WL_PAGE_EXERCISE_SECTIONS_CONTAINER_SELECTOR);
    const exerciseSectionsContainerParent = exerciseSectionsContainer == null ? void 0 : exerciseSectionsContainer.parentNode;
    const additionsElem = document.createElement("div");
    additionsElem.id = ELEM_PAGE_EXERCISE_SECTIONS_TOOLBAR_CONTAINER_ID;
    exerciseSectionsContainerParent == null ? void 0 : exerciseSectionsContainerParent.insertBefore(additionsElem, exerciseSectionsContainer);
  }
  function prepareExerciseExploreSectionPageToolbar() {
    const exerciseSectionsContainer = document.querySelector(ELEM_WL_PAGE_EXERCISE_EXPLORE_SECTION_CONTAINER_SELECTOR);
    const exerciseSectionsContainerParent = exerciseSectionsContainer == null ? void 0 : exerciseSectionsContainer.parentNode;
    const additionsElem = document.createElement("div");
    additionsElem.id = ELEM_PAGE_EXERCISE_EXPLORE_SECTIONS_TOOLBAR_CONTAINER_ID;
    exerciseSectionsContainerParent == null ? void 0 : exerciseSectionsContainerParent.insertBefore(additionsElem, exerciseSectionsContainer);
  }
  function prepareExercisePageSections() {
    const exerciseTitleElement = document.querySelector(ELEM_WL_PAGE_EXERCISE_TITLE_SELECTOR);
    const exerciseTitle = exerciseTitleElement ? exerciseTitleElement.innerText : "Unknown exercise";
    const exerciseSectionRows = document.querySelectorAll(ELEM_WL_PAGE_EXERCISE_SECTION_ROWS_SELECTOR);
    const addedElementsInfo = [];
    exerciseSectionRows.forEach((curSectionRowElem) => {
      const practiceBtnElem = curSectionRowElem.querySelector(ELEM_WL_PAGE_EXERCISE_SECTION_ROW_PRACTICE_ANCHOR_SELECTOR);
      const practiceBtnElemParent = practiceBtnElem == null ? void 0 : practiceBtnElem.parentNode;
      const sectionNameElem = practiceBtnElemParent == null ? void 0 : practiceBtnElemParent.querySelector(ELEM_WL_PAGE_EXERCISE_SECTION_ROW_ANCHOR_SELECTOR);
      const matchIDs = practiceBtnElem == null ? void 0 : practiceBtnElem.href.match(RE_PAGE_EXERCISE_PRACTICE_LINK);
      if (!practiceBtnElem || !practiceBtnElemParent || !sectionNameElem || !matchIDs) {
        return;
      }
      const additionsElem = document.createElement("div");
      additionsElem.id = `${ELEM_PAGE_EXERCISE_SECTIONS_ADDITION_BASE_ID}-${matchIDs[1]}-${matchIDs[2]}`;
      practiceBtnElemParent.insertBefore(additionsElem, practiceBtnElem.nextSibling);
      addedElementsInfo.push({
        elementID: additionsElem.id,
        exerciseID: matchIDs[1],
        sectionID: matchIDs[2],
        exerciseTitle,
        sectionTitle: sectionNameElem.innerText
      });
    });
    return addedElementsInfo;
  }
  function verifyOnPageExercise(address) {
    if (address) {
      return /\/exercise\/\d+$/.test(address);
    } else {
      return /\/exercise\/\d+$/.test(window.location.pathname);
    }
  }
  function verifyOnPageExerciseExploreSection(address) {
    if (address) {
      return /\/exercise\/\d+\/section\/\d+/.test(address);
    } else {
      return /\/exercise\/\d+\/section\/\d+/.test(window.location.pathname);
    }
  }
  function verifyOnPagePractice(address) {
    if (address) {
      return /\/practice\/\d+\/[\d,]+\/question\/\d+/.test(address);
    } else {
      return /\/practice\/\d+\/[\d,]+\/question\/\d+/.test(window.location.pathname);
    }
  }
  function verifyOnPagePracticeEnd(address) {
    if (address) {
      return /\/practice\/\d+\/[\d,]+\/practice\/end/.test(address);
    } else {
      return /\/practice\/\d+\/[\d,]+\/practice\/end/.test(window.location.pathname);
    }
  }
  function verifyOnLoggedInPage(address) {
    if (address) {
      return /^\/(user\/(profile|edit)|(exercise|practice)\/\d+|public\/(exercise|charts|user|reviews))/.test(address);
    } else {
      return /^\/(user\/(profile|edit)|(exercise|practice)\/\d+|public\/(exercise|charts|user|reviews))/.test(window.location.pathname);
    }
  }
  var sha256$1 = { exports: {} };
  function commonjsRequire(path) {
    throw new Error('Could not dynamically require "' + path + '". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.');
  }
  var core = { exports: {} };
  const __viteBrowserExternal = {};
  const __viteBrowserExternal$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
    __proto__: null,
    default: __viteBrowserExternal
  }, Symbol.toStringTag, { value: "Module" }));
  const require$$0 = /* @__PURE__ */ getAugmentedNamespace(__viteBrowserExternal$1);
  var hasRequiredCore;
  function requireCore() {
    if (hasRequiredCore)
      return core.exports;
    hasRequiredCore = 1;
    (function(module, exports) {
      (function(root, factory) {
        {
          module.exports = factory();
        }
      })(commonjsGlobal, function() {
        var CryptoJS = CryptoJS || function(Math2, undefined$1) {
          var crypto2;
          if (typeof window !== "undefined" && window.crypto) {
            crypto2 = window.crypto;
          }
          if (typeof self !== "undefined" && self.crypto) {
            crypto2 = self.crypto;
          }
          if (typeof globalThis !== "undefined" && globalThis.crypto) {
            crypto2 = globalThis.crypto;
          }
          if (!crypto2 && typeof window !== "undefined" && window.msCrypto) {
            crypto2 = window.msCrypto;
          }
          if (!crypto2 && typeof commonjsGlobal !== "undefined" && commonjsGlobal.crypto) {
            crypto2 = commonjsGlobal.crypto;
          }
          if (!crypto2 && typeof commonjsRequire === "function") {
            try {
              crypto2 = require$$0;
            } catch (err) {
            }
          }
          var cryptoSecureRandomInt = function() {
            if (crypto2) {
              if (typeof crypto2.getRandomValues === "function") {
                try {
                  return crypto2.getRandomValues(new Uint32Array(1))[0];
                } catch (err) {
                }
              }
              if (typeof crypto2.randomBytes === "function") {
                try {
                  return crypto2.randomBytes(4).readInt32LE();
                } catch (err) {
                }
              }
            }
            throw new Error("Native crypto module could not be used to get secure random number.");
          };
          var create = Object.create || function() {
            function F2() {
            }
            return function(obj) {
              var subtype;
              F2.prototype = obj;
              subtype = new F2();
              F2.prototype = null;
              return subtype;
            };
          }();
          var C2 = {};
          var C_lib = C2.lib = {};
          var Base = C_lib.Base = function() {
            return {
              /**
               * Creates a new object that inherits from this object.
               *
               * @param {Object} overrides Properties to copy into the new object.
               *
               * @return {Object} The new object.
               *
               * @static
               *
               * @example
               *
               *     var MyType = CryptoJS.lib.Base.extend({
               *         field: 'value',
               *
               *         method: function () {
               *         }
               *     });
               */
              extend: function(overrides) {
                var subtype = create(this);
                if (overrides) {
                  subtype.mixIn(overrides);
                }
                if (!subtype.hasOwnProperty("init") || this.init === subtype.init) {
                  subtype.init = function() {
                    subtype.$super.init.apply(this, arguments);
                  };
                }
                subtype.init.prototype = subtype;
                subtype.$super = this;
                return subtype;
              },
              /**
               * Extends this object and runs the init method.
               * Arguments to create() will be passed to init().
               *
               * @return {Object} The new object.
               *
               * @static
               *
               * @example
               *
               *     var instance = MyType.create();
               */
              create: function() {
                var instance2 = this.extend();
                instance2.init.apply(instance2, arguments);
                return instance2;
              },
              /**
               * Initializes a newly created object.
               * Override this method to add some logic when your objects are created.
               *
               * @example
               *
               *     var MyType = CryptoJS.lib.Base.extend({
               *         init: function () {
               *             // ...
               *         }
               *     });
               */
              init: function() {
              },
              /**
               * Copies properties into this object.
               *
               * @param {Object} properties The properties to mix in.
               *
               * @example
               *
               *     MyType.mixIn({
               *         field: 'value'
               *     });
               */
              mixIn: function(properties2) {
                for (var propertyName in properties2) {
                  if (properties2.hasOwnProperty(propertyName)) {
                    this[propertyName] = properties2[propertyName];
                  }
                }
                if (properties2.hasOwnProperty("toString")) {
                  this.toString = properties2.toString;
                }
              },
              /**
               * Creates a copy of this object.
               *
               * @return {Object} The clone.
               *
               * @example
               *
               *     var clone = instance.clone();
               */
              clone: function() {
                return this.init.prototype.extend(this);
              }
            };
          }();
          var WordArray = C_lib.WordArray = Base.extend({
            /**
             * Initializes a newly created word array.
             *
             * @param {Array} words (Optional) An array of 32-bit words.
             * @param {number} sigBytes (Optional) The number of significant bytes in the words.
             *
             * @example
             *
             *     var wordArray = CryptoJS.lib.WordArray.create();
             *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
             *     var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
             */
            init: function(words, sigBytes) {
              words = this.words = words || [];
              if (sigBytes != undefined$1) {
                this.sigBytes = sigBytes;
              } else {
                this.sigBytes = words.length * 4;
              }
            },
            /**
             * Converts this word array to a string.
             *
             * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
             *
             * @return {string} The stringified word array.
             *
             * @example
             *
             *     var string = wordArray + '';
             *     var string = wordArray.toString();
             *     var string = wordArray.toString(CryptoJS.enc.Utf8);
             */
            toString: function(encoder) {
              return (encoder || Hex).stringify(this);
            },
            /**
             * Concatenates a word array to this word array.
             *
             * @param {WordArray} wordArray The word array to append.
             *
             * @return {WordArray} This word array.
             *
             * @example
             *
             *     wordArray1.concat(wordArray2);
             */
            concat: function(wordArray) {
              var thisWords = this.words;
              var thatWords = wordArray.words;
              var thisSigBytes = this.sigBytes;
              var thatSigBytes = wordArray.sigBytes;
              this.clamp();
              if (thisSigBytes % 4) {
                for (var i2 = 0; i2 < thatSigBytes; i2++) {
                  var thatByte = thatWords[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
                  thisWords[thisSigBytes + i2 >>> 2] |= thatByte << 24 - (thisSigBytes + i2) % 4 * 8;
                }
              } else {
                for (var j2 = 0; j2 < thatSigBytes; j2 += 4) {
                  thisWords[thisSigBytes + j2 >>> 2] = thatWords[j2 >>> 2];
                }
              }
              this.sigBytes += thatSigBytes;
              return this;
            },
            /**
             * Removes insignificant bits.
             *
             * @example
             *
             *     wordArray.clamp();
             */
            clamp: function() {
              var words = this.words;
              var sigBytes = this.sigBytes;
              words[sigBytes >>> 2] &= 4294967295 << 32 - sigBytes % 4 * 8;
              words.length = Math2.ceil(sigBytes / 4);
            },
            /**
             * Creates a copy of this word array.
             *
             * @return {WordArray} The clone.
             *
             * @example
             *
             *     var clone = wordArray.clone();
             */
            clone: function() {
              var clone = Base.clone.call(this);
              clone.words = this.words.slice(0);
              return clone;
            },
            /**
             * Creates a word array filled with random bytes.
             *
             * @param {number} nBytes The number of random bytes to generate.
             *
             * @return {WordArray} The random word array.
             *
             * @static
             *
             * @example
             *
             *     var wordArray = CryptoJS.lib.WordArray.random(16);
             */
            random: function(nBytes) {
              var words = [];
              for (var i2 = 0; i2 < nBytes; i2 += 4) {
                words.push(cryptoSecureRandomInt());
              }
              return new WordArray.init(words, nBytes);
            }
          });
          var C_enc = C2.enc = {};
          var Hex = C_enc.Hex = {
            /**
             * Converts a word array to a hex string.
             *
             * @param {WordArray} wordArray The word array.
             *
             * @return {string} The hex string.
             *
             * @static
             *
             * @example
             *
             *     var hexString = CryptoJS.enc.Hex.stringify(wordArray);
             */
            stringify: function(wordArray) {
              var words = wordArray.words;
              var sigBytes = wordArray.sigBytes;
              var hexChars = [];
              for (var i2 = 0; i2 < sigBytes; i2++) {
                var bite = words[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
                hexChars.push((bite >>> 4).toString(16));
                hexChars.push((bite & 15).toString(16));
              }
              return hexChars.join("");
            },
            /**
             * Converts a hex string to a word array.
             *
             * @param {string} hexStr The hex string.
             *
             * @return {WordArray} The word array.
             *
             * @static
             *
             * @example
             *
             *     var wordArray = CryptoJS.enc.Hex.parse(hexString);
             */
            parse: function(hexStr) {
              var hexStrLength = hexStr.length;
              var words = [];
              for (var i2 = 0; i2 < hexStrLength; i2 += 2) {
                words[i2 >>> 3] |= parseInt(hexStr.substr(i2, 2), 16) << 24 - i2 % 8 * 4;
              }
              return new WordArray.init(words, hexStrLength / 2);
            }
          };
          var Latin1 = C_enc.Latin1 = {
            /**
             * Converts a word array to a Latin1 string.
             *
             * @param {WordArray} wordArray The word array.
             *
             * @return {string} The Latin1 string.
             *
             * @static
             *
             * @example
             *
             *     var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
             */
            stringify: function(wordArray) {
              var words = wordArray.words;
              var sigBytes = wordArray.sigBytes;
              var latin1Chars = [];
              for (var i2 = 0; i2 < sigBytes; i2++) {
                var bite = words[i2 >>> 2] >>> 24 - i2 % 4 * 8 & 255;
                latin1Chars.push(String.fromCharCode(bite));
              }
              return latin1Chars.join("");
            },
            /**
             * Converts a Latin1 string to a word array.
             *
             * @param {string} latin1Str The Latin1 string.
             *
             * @return {WordArray} The word array.
             *
             * @static
             *
             * @example
             *
             *     var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
             */
            parse: function(latin1Str) {
              var latin1StrLength = latin1Str.length;
              var words = [];
              for (var i2 = 0; i2 < latin1StrLength; i2++) {
                words[i2 >>> 2] |= (latin1Str.charCodeAt(i2) & 255) << 24 - i2 % 4 * 8;
              }
              return new WordArray.init(words, latin1StrLength);
            }
          };
          var Utf8 = C_enc.Utf8 = {
            /**
             * Converts a word array to a UTF-8 string.
             *
             * @param {WordArray} wordArray The word array.
             *
             * @return {string} The UTF-8 string.
             *
             * @static
             *
             * @example
             *
             *     var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
             */
            stringify: function(wordArray) {
              try {
                return decodeURIComponent(escape(Latin1.stringify(wordArray)));
              } catch (e2) {
                throw new Error("Malformed UTF-8 data");
              }
            },
            /**
             * Converts a UTF-8 string to a word array.
             *
             * @param {string} utf8Str The UTF-8 string.
             *
             * @return {WordArray} The word array.
             *
             * @static
             *
             * @example
             *
             *     var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
             */
            parse: function(utf8Str) {
              return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
            }
          };
          var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
            /**
             * Resets this block algorithm's data buffer to its initial state.
             *
             * @example
             *
             *     bufferedBlockAlgorithm.reset();
             */
            reset: function() {
              this._data = new WordArray.init();
              this._nDataBytes = 0;
            },
            /**
             * Adds new data to this block algorithm's buffer.
             *
             * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
             *
             * @example
             *
             *     bufferedBlockAlgorithm._append('data');
             *     bufferedBlockAlgorithm._append(wordArray);
             */
            _append: function(data) {
              if (typeof data == "string") {
                data = Utf8.parse(data);
              }
              this._data.concat(data);
              this._nDataBytes += data.sigBytes;
            },
            /**
             * Processes available data blocks.
             *
             * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
             *
             * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
             *
             * @return {WordArray} The processed data.
             *
             * @example
             *
             *     var processedData = bufferedBlockAlgorithm._process();
             *     var processedData = bufferedBlockAlgorithm._process(!!'flush');
             */
            _process: function(doFlush) {
              var processedWords;
              var data = this._data;
              var dataWords = data.words;
              var dataSigBytes = data.sigBytes;
              var blockSize = this.blockSize;
              var blockSizeBytes = blockSize * 4;
              var nBlocksReady = dataSigBytes / blockSizeBytes;
              if (doFlush) {
                nBlocksReady = Math2.ceil(nBlocksReady);
              } else {
                nBlocksReady = Math2.max((nBlocksReady | 0) - this._minBufferSize, 0);
              }
              var nWordsReady = nBlocksReady * blockSize;
              var nBytesReady = Math2.min(nWordsReady * 4, dataSigBytes);
              if (nWordsReady) {
                for (var offset = 0; offset < nWordsReady; offset += blockSize) {
                  this._doProcessBlock(dataWords, offset);
                }
                processedWords = dataWords.splice(0, nWordsReady);
                data.sigBytes -= nBytesReady;
              }
              return new WordArray.init(processedWords, nBytesReady);
            },
            /**
             * Creates a copy of this object.
             *
             * @return {Object} The clone.
             *
             * @example
             *
             *     var clone = bufferedBlockAlgorithm.clone();
             */
            clone: function() {
              var clone = Base.clone.call(this);
              clone._data = this._data.clone();
              return clone;
            },
            _minBufferSize: 0
          });
          C_lib.Hasher = BufferedBlockAlgorithm.extend({
            /**
             * Configuration options.
             */
            cfg: Base.extend(),
            /**
             * Initializes a newly created hasher.
             *
             * @param {Object} cfg (Optional) The configuration options to use for this hash computation.
             *
             * @example
             *
             *     var hasher = CryptoJS.algo.SHA256.create();
             */
            init: function(cfg) {
              this.cfg = this.cfg.extend(cfg);
              this.reset();
            },
            /**
             * Resets this hasher to its initial state.
             *
             * @example
             *
             *     hasher.reset();
             */
            reset: function() {
              BufferedBlockAlgorithm.reset.call(this);
              this._doReset();
            },
            /**
             * Updates this hasher with a message.
             *
             * @param {WordArray|string} messageUpdate The message to append.
             *
             * @return {Hasher} This hasher.
             *
             * @example
             *
             *     hasher.update('message');
             *     hasher.update(wordArray);
             */
            update: function(messageUpdate) {
              this._append(messageUpdate);
              this._process();
              return this;
            },
            /**
             * Finalizes the hash computation.
             * Note that the finalize operation is effectively a destructive, read-once operation.
             *
             * @param {WordArray|string} messageUpdate (Optional) A final message update.
             *
             * @return {WordArray} The hash.
             *
             * @example
             *
             *     var hash = hasher.finalize();
             *     var hash = hasher.finalize('message');
             *     var hash = hasher.finalize(wordArray);
             */
            finalize: function(messageUpdate) {
              if (messageUpdate) {
                this._append(messageUpdate);
              }
              var hash = this._doFinalize();
              return hash;
            },
            blockSize: 512 / 32,
            /**
             * Creates a shortcut function to a hasher's object interface.
             *
             * @param {Hasher} hasher The hasher to create a helper for.
             *
             * @return {Function} The shortcut function.
             *
             * @static
             *
             * @example
             *
             *     var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
             */
            _createHelper: function(hasher) {
              return function(message, cfg) {
                return new hasher.init(cfg).finalize(message);
              };
            },
            /**
             * Creates a shortcut function to the HMAC's object interface.
             *
             * @param {Hasher} hasher The hasher to use in this HMAC helper.
             *
             * @return {Function} The shortcut function.
             *
             * @static
             *
             * @example
             *
             *     var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
             */
            _createHmacHelper: function(hasher) {
              return function(message, key) {
                return new C_algo.HMAC.init(hasher, key).finalize(message);
              };
            }
          });
          var C_algo = C2.algo = {};
          return C2;
        }(Math);
        return CryptoJS;
      });
    })(core);
    return core.exports;
  }
  (function(module, exports) {
    (function(root, factory) {
      {
        module.exports = factory(requireCore());
      }
    })(commonjsGlobal, function(CryptoJS) {
      (function(Math2) {
        var C2 = CryptoJS;
        var C_lib = C2.lib;
        var WordArray = C_lib.WordArray;
        var Hasher = C_lib.Hasher;
        var C_algo = C2.algo;
        var H2 = [];
        var K2 = [];
        (function() {
          function isPrime(n3) {
            var sqrtN = Math2.sqrt(n3);
            for (var factor = 2; factor <= sqrtN; factor++) {
              if (!(n3 % factor)) {
                return false;
              }
            }
            return true;
          }
          function getFractionalBits(n3) {
            return (n3 - (n3 | 0)) * 4294967296 | 0;
          }
          var n2 = 2;
          var nPrime = 0;
          while (nPrime < 64) {
            if (isPrime(n2)) {
              if (nPrime < 8) {
                H2[nPrime] = getFractionalBits(Math2.pow(n2, 1 / 2));
              }
              K2[nPrime] = getFractionalBits(Math2.pow(n2, 1 / 3));
              nPrime++;
            }
            n2++;
          }
        })();
        var W2 = [];
        var SHA256 = C_algo.SHA256 = Hasher.extend({
          _doReset: function() {
            this._hash = new WordArray.init(H2.slice(0));
          },
          _doProcessBlock: function(M2, offset) {
            var H3 = this._hash.words;
            var a2 = H3[0];
            var b2 = H3[1];
            var c2 = H3[2];
            var d2 = H3[3];
            var e2 = H3[4];
            var f2 = H3[5];
            var g2 = H3[6];
            var h2 = H3[7];
            for (var i2 = 0; i2 < 64; i2++) {
              if (i2 < 16) {
                W2[i2] = M2[offset + i2] | 0;
              } else {
                var gamma0x = W2[i2 - 15];
                var gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3;
                var gamma1x = W2[i2 - 2];
                var gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10;
                W2[i2] = gamma0 + W2[i2 - 7] + gamma1 + W2[i2 - 16];
              }
              var ch = e2 & f2 ^ ~e2 & g2;
              var maj = a2 & b2 ^ a2 & c2 ^ b2 & c2;
              var sigma0 = (a2 << 30 | a2 >>> 2) ^ (a2 << 19 | a2 >>> 13) ^ (a2 << 10 | a2 >>> 22);
              var sigma1 = (e2 << 26 | e2 >>> 6) ^ (e2 << 21 | e2 >>> 11) ^ (e2 << 7 | e2 >>> 25);
              var t1 = h2 + sigma1 + ch + K2[i2] + W2[i2];
              var t2 = sigma0 + maj;
              h2 = g2;
              g2 = f2;
              f2 = e2;
              e2 = d2 + t1 | 0;
              d2 = c2;
              c2 = b2;
              b2 = a2;
              a2 = t1 + t2 | 0;
            }
            H3[0] = H3[0] + a2 | 0;
            H3[1] = H3[1] + b2 | 0;
            H3[2] = H3[2] + c2 | 0;
            H3[3] = H3[3] + d2 | 0;
            H3[4] = H3[4] + e2 | 0;
            H3[5] = H3[5] + f2 | 0;
            H3[6] = H3[6] + g2 | 0;
            H3[7] = H3[7] + h2 | 0;
          },
          _doFinalize: function() {
            var data = this._data;
            var dataWords = data.words;
            var nBitsTotal = this._nDataBytes * 8;
            var nBitsLeft = data.sigBytes * 8;
            dataWords[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32;
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math2.floor(nBitsTotal / 4294967296);
            dataWords[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal;
            data.sigBytes = dataWords.length * 4;
            this._process();
            return this._hash;
          },
          clone: function() {
            var clone = Hasher.clone.call(this);
            clone._hash = this._hash.clone();
            return clone;
          }
        });
        C2.SHA256 = Hasher._createHelper(SHA256);
        C2.HmacSHA256 = Hasher._createHmacHelper(SHA256);
      })(Math);
      return CryptoJS.SHA256;
    });
  })(sha256$1);
  var sha256Exports = sha256$1.exports;
  const sha256 = /* @__PURE__ */ getDefaultExportFromCjs(sha256Exports);
  function isDateToday(dateObject) {
    const today = /* @__PURE__ */ new Date();
    return dateObject.getFullYear() === today.getFullYear() && dateObject.getMonth() === today.getMonth() && dateObject.getDate() === today.getDate();
  }
  function getSectionKeysFromSelectionContext({
    selectedSections
  }) {
    return selectedSections.reduce((acc, {
      sectionID
    }) => {
      return [...acc, sectionID];
    }, []);
  }
  function getCustomSelectionFromHash({
    hash,
    sectionSelectionContext
  }) {
    const customSelectionFound = sectionSelectionContext.customSelectionsStorage.filter((props) => hash === props.hash);
    return customSelectionFound ? customSelectionFound[0] : null;
  }
  function filterCustomSelectionFromHash({
    hash,
    sectionSelectionContext
  }) {
    const customSelectionFiltered = sectionSelectionContext.customSelectionsStorage.filter((props) => hash !== props.hash);
    return customSelectionFiltered ? customSelectionFiltered : [];
  }
  function filterCustomSelectionFromExerciseID({
    exerciseID,
    sectionSelectionContext
  }) {
    const customSelectionFiltered = sectionSelectionContext.customSelectionsStorage.filter((props) => exerciseID !== props.exerciseID);
    return customSelectionFiltered ? customSelectionFiltered : [];
  }
  function getCustomSelectionsFromExerciseID({
    exerciseID,
    sectionSelectionContext
  }) {
    const customSelectionFound = sectionSelectionContext.customSelectionsStorage.filter((props) => exerciseID === props.exerciseID);
    return customSelectionFound ? customSelectionFound : [];
  }
  function getCustomSelectionExerciseFromID({
    exerciseID,
    sectionSelectionContext
  }) {
    const customSelectionExerciseFound = sectionSelectionContext.customSelectionsExercisesStorage.filter((props) => exerciseID === props.exerciseID);
    return customSelectionExerciseFound ? customSelectionExerciseFound[0] : null;
  }
  function filterCustomSelectionExerciseFromID({
    exerciseID,
    sectionSelectionContext
  }) {
    const customSelectionExerciseFiltered = sectionSelectionContext.customSelectionsExercisesStorage.filter((props) => exerciseID !== props.exerciseID);
    return customSelectionExerciseFiltered ? customSelectionExerciseFiltered : [];
  }
  function getCheckboxIdFromExerciseAndSection({
    exerciseID,
    sectionID
  }) {
    return `${ELEM_PAGE_EXERCISE_SECTIONS_ADDITION_BASE_ID}-${exerciseID}-${sectionID}-checkbox`;
  }
  function propFilterExerciseID(matchingExerciseID) {
    return (filterProp) => matchingExerciseID === filterProp.exerciseID;
  }
  function propFilterCustomSelectionHash(matchingHash) {
    return (filterProp) => matchingHash === filterProp.hash;
  }
  function propFilterElementID(matchingElementID) {
    return (filterProp) => matchingElementID === filterProp.elementID;
  }
  function propFilterSectionID(matchingSectionID) {
    return (filterProp) => matchingSectionID === filterProp.sectionID;
  }
  function sectionsMapperRestoreElementIDs(currentExerciseID) {
    return (section) => {
      return {
        ...section,
        elementID: getCheckboxIdFromExerciseAndSection({
          exerciseID: currentExerciseID,
          sectionID: section.sectionID
        })
      };
    };
  }
  function getTitleFromExerciseID({
    exerciseID,
    sectionSelectionContext
  }) {
    var _a2;
    return ((_a2 = getCustomSelectionExerciseFromID({
      exerciseID,
      sectionSelectionContext
    })) == null ? void 0 : _a2.exerciseTitle) ?? `Exercise #${exerciseID}`;
  }
  function getDefinedCustomSelectionStatistics(customSelection) {
    return {
      lastPracticed: customSelection.lastPracticed ? customSelection.lastPracticed : null,
      practicesToday: customSelection.practicesToday && customSelection.lastPracticed && isDateToday(new Date(customSelection.lastPracticed)) ? customSelection.practicesToday : 0,
      practicesTotal: customSelection.practicesTotal ? customSelection.practicesTotal : 0
    };
  }
  function getCustomSelectionHash({
    exerciseID,
    sectionsKeys
  }) {
    sectionsKeys.sort();
    return sha256(`${exerciseID}:${sectionsKeys.join("_")}`).toString();
  }
  function getCustomSelectionHashFromSelectionContext({
    selectedExercise,
    selectedSections
  }) {
    return getCustomSelectionHash({
      exerciseID: selectedExercise.exerciseID,
      sectionsKeys: getSectionKeysFromSelectionContext({
        selectedSections
      })
    });
  }
  function logNotification({
    title: title2,
    text,
    type
  }) {
    let preMessage = "WLE Undefined";
    if (type === NotificationType.NOTIFICATION) {
      preMessage = "WLE Info";
    } else if (type === NotificationType.ERROR) {
      preMessage = "WLE Error";
    } else if (type === NotificationType.WARNING) {
      preMessage = "WLE Warning";
    }
    console.log(`${preMessage} :: (${title2}) ${text}`);
  }
  function _extends() {
    _extends = Object.assign ? Object.assign.bind() : function(target) {
      for (var i2 = 1; i2 < arguments.length; i2++) {
        var source = arguments[i2];
        for (var key in source) {
          if (Object.prototype.hasOwnProperty.call(source, key)) {
            target[key] = source[key];
          }
        }
      }
      return target;
    };
    return _extends.apply(this, arguments);
  }
  function $6ed0406888f73fc4$var$setRef(ref2, value) {
    if (typeof ref2 === "function")
      ref2(value);
    else if (ref2 !== null && ref2 !== void 0)
      ref2.current = value;
  }
  function $6ed0406888f73fc4$export$43e446d32b3d21af(...refs) {
    return (node) => refs.forEach(
      (ref2) => $6ed0406888f73fc4$var$setRef(ref2, node)
    );
  }
  function $6ed0406888f73fc4$export$c7b2cbe3552a0d05(...refs) {
    return T$1($6ed0406888f73fc4$export$43e446d32b3d21af(...refs), refs);
  }
  function $c512c27ab02ef895$export$50c7b4e9d9f19c1(scopeName, createContextScopeDeps = []) {
    let defaultContexts = [];
    function $c512c27ab02ef895$export$fd42f52fd3ae1109(rootComponentName, defaultContext) {
      const BaseContext = /* @__PURE__ */ G$1(defaultContext);
      const index2 = defaultContexts.length;
      defaultContexts = [
        ...defaultContexts,
        defaultContext
      ];
      function Provider2(props) {
        const { scope, children, ...context } = props;
        const Context2 = (scope === null || scope === void 0 ? void 0 : scope[scopeName][index2]) || BaseContext;
        const value = F$1(
          () => context,
          Object.values(context)
        );
        return /* @__PURE__ */ y$1(Context2.Provider, {
          value
        }, children);
      }
      function useContext(consumerName, scope) {
        const Context2 = (scope === null || scope === void 0 ? void 0 : scope[scopeName][index2]) || BaseContext;
        const context = q$1(Context2);
        if (context)
          return context;
        if (defaultContext !== void 0)
          return defaultContext;
        throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``);
      }
      Provider2.displayName = rootComponentName + "Provider";
      return [
        Provider2,
        useContext
      ];
    }
    const createScope = () => {
      const scopeContexts = defaultContexts.map((defaultContext) => {
        return /* @__PURE__ */ G$1(defaultContext);
      });
      return function useScope(scope) {
        const contexts = (scope === null || scope === void 0 ? void 0 : scope[scopeName]) || scopeContexts;
        return F$1(
          () => ({
            [`__scope${scopeName}`]: {
              ...scope,
              [scopeName]: contexts
            }
          }),
          [
            scope,
            contexts
          ]
        );
      };
    };
    createScope.scopeName = scopeName;
    return [
      $c512c27ab02ef895$export$fd42f52fd3ae1109,
      $c512c27ab02ef895$var$composeContextScopes(createScope, ...createContextScopeDeps)
    ];
  }
  function $c512c27ab02ef895$var$composeContextScopes(...scopes) {
    const baseScope = scopes[0];
    if (scopes.length === 1)
      return baseScope;
    const createScope1 = () => {
      const scopeHooks = scopes.map(
        (createScope) => ({
          useScope: createScope(),
          scopeName: createScope.scopeName
        })
      );
      return function useComposedScopes(overrideScopes) {
        const nextScopes1 = scopeHooks.reduce((nextScopes, { useScope, scopeName }) => {
          const scopeProps = useScope(overrideScopes);
          const currentScope = scopeProps[`__scope${scopeName}`];
          return {
            ...nextScopes,
            ...currentScope
          };
        }, {});
        return F$1(
          () => ({
            [`__scope${baseScope.scopeName}`]: nextScopes1
          }),
          [
            nextScopes1
          ]
        );
      };
    };
    createScope1.scopeName = baseScope.scopeName;
    return createScope1;
  }
  function $e42e1063c40fb3ef$export$b9ecd428b558ff10(originalEventHandler, ourEventHandler, { checkForDefaultPrevented = true } = {}) {
    return function handleEvent(event) {
      originalEventHandler === null || originalEventHandler === void 0 || originalEventHandler(event);
      if (checkForDefaultPrevented === false || !event.defaultPrevented)
        return ourEventHandler === null || ourEventHandler === void 0 ? void 0 : ourEventHandler(event);
    };
  }
  function $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(callback) {
    const callbackRef = _$2(callback);
    p(() => {
      callbackRef.current = callback;
    });
    return F$1(
      () => (...args) => {
        var _callbackRef$current;
        return (_callbackRef$current = callbackRef.current) === null || _callbackRef$current === void 0 ? void 0 : _callbackRef$current.call(callbackRef, ...args);
      },
      []
    );
  }
  function $71cd76cc60e0454e$export$6f32135080cb4c3({ prop, defaultProp, onChange = () => {
  } }) {
    const [uncontrolledProp, setUncontrolledProp] = $71cd76cc60e0454e$var$useUncontrolledState({
      defaultProp,
      onChange
    });
    const isControlled = prop !== void 0;
    const value1 = isControlled ? prop : uncontrolledProp;
    const handleChange = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onChange);
    const setValue = T$1((nextValue) => {
      if (isControlled) {
        const setter = nextValue;
        const value = typeof nextValue === "function" ? setter(prop) : nextValue;
        if (value !== prop)
          handleChange(value);
      } else
        setUncontrolledProp(nextValue);
    }, [
      isControlled,
      prop,
      setUncontrolledProp,
      handleChange
    ]);
    return [
      value1,
      setValue
    ];
  }
  function $71cd76cc60e0454e$var$useUncontrolledState({ defaultProp, onChange }) {
    const uncontrolledState = h(defaultProp);
    const [value] = uncontrolledState;
    const prevValueRef = _$2(value);
    const handleChange = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onChange);
    p(() => {
      if (prevValueRef.current !== value) {
        handleChange(value);
        prevValueRef.current = value;
      }
    }, [
      value,
      prevValueRef,
      handleChange
    ]);
    return uncontrolledState;
  }
  function $010c2913dbd2fe3d$export$5cae361ad82dce8b(value) {
    const ref2 = _$2({
      value,
      previous: value
    });
    return F$1(() => {
      if (ref2.current.value !== value) {
        ref2.current.previous = ref2.current.value;
        ref2.current.value = value;
      }
      return ref2.current.previous;
    }, [
      value
    ]);
  }
  const $9f79659886946c16$export$e5c5a5f917a5871c = Boolean(globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) ? y : () => {
  };
  function $db6c3485150b8e66$export$1ab7ae714698c4b8(element) {
    const [size, setSize] = h(void 0);
    $9f79659886946c16$export$e5c5a5f917a5871c(() => {
      if (element) {
        setSize({
          width: element.offsetWidth,
          height: element.offsetHeight
        });
        const resizeObserver = new ResizeObserver((entries) => {
          if (!Array.isArray(entries))
            return;
          if (!entries.length)
            return;
          const entry = entries[0];
          let width;
          let height;
          if ("borderBoxSize" in entry) {
            const borderSizeEntry = entry["borderBoxSize"];
            const borderSize = Array.isArray(borderSizeEntry) ? borderSizeEntry[0] : borderSizeEntry;
            width = borderSize["inlineSize"];
            height = borderSize["blockSize"];
          } else {
            width = element.offsetWidth;
            height = element.offsetHeight;
          }
          setSize({
            width,
            height
          });
        });
        resizeObserver.observe(element, {
          box: "border-box"
        });
        return () => resizeObserver.unobserve(element);
      } else
        setSize(void 0);
    }, [
      element
    ]);
    return size;
  }
  function $fe963b355347cc68$export$3e6543de14f8614f(initialState, machine) {
    return s((state, event) => {
      const nextState = machine[state][event];
      return nextState !== null && nextState !== void 0 ? nextState : state;
    }, initialState);
  }
  const $921a889cee6df7e8$export$99c2b779aa4e8b8b = (props) => {
    const { present, children } = props;
    const presence = $921a889cee6df7e8$var$usePresence(present);
    const child2 = typeof children === "function" ? children({
      present: presence.isPresent
    }) : O.only(children);
    const ref2 = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(presence.ref, child2.ref);
    const forceMount = typeof children === "function";
    return forceMount || presence.isPresent ? /* @__PURE__ */ sn(child2, {
      ref: ref2
    }) : null;
  };
  $921a889cee6df7e8$export$99c2b779aa4e8b8b.displayName = "Presence";
  function $921a889cee6df7e8$var$usePresence(present) {
    const [node1, setNode] = h();
    const stylesRef = _$2({});
    const prevPresentRef = _$2(present);
    const prevAnimationNameRef = _$2("none");
    const initialState = present ? "mounted" : "unmounted";
    const [state, send] = $fe963b355347cc68$export$3e6543de14f8614f(initialState, {
      mounted: {
        UNMOUNT: "unmounted",
        ANIMATION_OUT: "unmountSuspended"
      },
      unmountSuspended: {
        MOUNT: "mounted",
        ANIMATION_END: "unmounted"
      },
      unmounted: {
        MOUNT: "mounted"
      }
    });
    p(() => {
      const currentAnimationName = $921a889cee6df7e8$var$getAnimationName(stylesRef.current);
      prevAnimationNameRef.current = state === "mounted" ? currentAnimationName : "none";
    }, [
      state
    ]);
    $9f79659886946c16$export$e5c5a5f917a5871c(() => {
      const styles2 = stylesRef.current;
      const wasPresent = prevPresentRef.current;
      const hasPresentChanged = wasPresent !== present;
      if (hasPresentChanged) {
        const prevAnimationName = prevAnimationNameRef.current;
        const currentAnimationName = $921a889cee6df7e8$var$getAnimationName(styles2);
        if (present)
          send("MOUNT");
        else if (currentAnimationName === "none" || (styles2 === null || styles2 === void 0 ? void 0 : styles2.display) === "none")
          send("UNMOUNT");
        else {
          const isAnimating = prevAnimationName !== currentAnimationName;
          if (wasPresent && isAnimating)
            send("ANIMATION_OUT");
          else
            send("UNMOUNT");
        }
        prevPresentRef.current = present;
      }
    }, [
      present,
      send
    ]);
    $9f79659886946c16$export$e5c5a5f917a5871c(() => {
      if (node1) {
        const handleAnimationEnd = (event) => {
          const currentAnimationName = $921a889cee6df7e8$var$getAnimationName(stylesRef.current);
          const isCurrentAnimation = currentAnimationName.includes(event.animationName);
          if (event.target === node1 && isCurrentAnimation)
            pn(
              () => send("ANIMATION_END")
            );
        };
        const handleAnimationStart = (event) => {
          if (event.target === node1)
            prevAnimationNameRef.current = $921a889cee6df7e8$var$getAnimationName(stylesRef.current);
        };
        node1.addEventListener("animationstart", handleAnimationStart);
        node1.addEventListener("animationcancel", handleAnimationEnd);
        node1.addEventListener("animationend", handleAnimationEnd);
        return () => {
          node1.removeEventListener("animationstart", handleAnimationStart);
          node1.removeEventListener("animationcancel", handleAnimationEnd);
          node1.removeEventListener("animationend", handleAnimationEnd);
        };
      } else
        send("ANIMATION_END");
    }, [
      node1,
      send
    ]);
    return {
      isPresent: [
        "mounted",
        "unmountSuspended"
      ].includes(state),
      ref: T$1((node) => {
        if (node)
          stylesRef.current = getComputedStyle(node);
        setNode(node);
      }, [])
    };
  }
  function $921a889cee6df7e8$var$getAnimationName(styles2) {
    return (styles2 === null || styles2 === void 0 ? void 0 : styles2.animationName) || "none";
  }
  const $5e63c961fc1ce211$export$8c6ed5c666ac1360 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { children, ...slotProps } = props;
    const childrenArray = O.toArray(children);
    const slottable = childrenArray.find($5e63c961fc1ce211$var$isSlottable);
    if (slottable) {
      const newElement = slottable.props.children;
      const newChildren = childrenArray.map((child2) => {
        if (child2 === slottable) {
          if (O.count(newElement) > 1)
            return O.only(null);
          return /* @__PURE__ */ an(newElement) ? newElement.props.children : null;
        } else
          return child2;
      });
      return /* @__PURE__ */ y$1($5e63c961fc1ce211$var$SlotClone, _extends({}, slotProps, {
        ref: forwardedRef
      }), /* @__PURE__ */ an(newElement) ? /* @__PURE__ */ sn(newElement, void 0, newChildren) : null);
    }
    return /* @__PURE__ */ y$1($5e63c961fc1ce211$var$SlotClone, _extends({}, slotProps, {
      ref: forwardedRef
    }), children);
  });
  $5e63c961fc1ce211$export$8c6ed5c666ac1360.displayName = "Slot";
  const $5e63c961fc1ce211$var$SlotClone = /* @__PURE__ */ k((props, forwardedRef) => {
    const { children, ...slotProps } = props;
    if (/* @__PURE__ */ an(children))
      return /* @__PURE__ */ sn(children, {
        ...$5e63c961fc1ce211$var$mergeProps(slotProps, children.props),
        ref: forwardedRef ? $6ed0406888f73fc4$export$43e446d32b3d21af(forwardedRef, children.ref) : children.ref
      });
    return O.count(children) > 1 ? O.only(null) : null;
  });
  $5e63c961fc1ce211$var$SlotClone.displayName = "SlotClone";
  const $5e63c961fc1ce211$export$d9f1ccf0bdb05d45 = ({ children }) => {
    return /* @__PURE__ */ y$1(k$2, null, children);
  };
  function $5e63c961fc1ce211$var$isSlottable(child2) {
    return /* @__PURE__ */ an(child2) && child2.type === $5e63c961fc1ce211$export$d9f1ccf0bdb05d45;
  }
  function $5e63c961fc1ce211$var$mergeProps(slotProps, childProps) {
    const overrideProps = {
      ...childProps
    };
    for (const propName in childProps) {
      const slotPropValue = slotProps[propName];
      const childPropValue = childProps[propName];
      const isHandler = /^on[A-Z]/.test(propName);
      if (isHandler) {
        if (slotPropValue && childPropValue)
          overrideProps[propName] = (...args) => {
            childPropValue(...args);
            slotPropValue(...args);
          };
        else if (slotPropValue)
          overrideProps[propName] = slotPropValue;
      } else if (propName === "style")
        overrideProps[propName] = {
          ...slotPropValue,
          ...childPropValue
        };
      else if (propName === "className")
        overrideProps[propName] = [
          slotPropValue,
          childPropValue
        ].filter(Boolean).join(" ");
    }
    return {
      ...slotProps,
      ...overrideProps
    };
  }
  const $8927f6f2acc4f386$var$NODES = [
    "a",
    "button",
    "div",
    "form",
    "h2",
    "h3",
    "img",
    "input",
    "label",
    "li",
    "nav",
    "ol",
    "p",
    "span",
    "svg",
    "ul"
  ];
  const $8927f6f2acc4f386$export$250ffa63cdc0d034 = $8927f6f2acc4f386$var$NODES.reduce((primitive, node) => {
    const Node = /* @__PURE__ */ k((props, forwardedRef) => {
      const { asChild, ...primitiveProps } = props;
      const Comp = asChild ? $5e63c961fc1ce211$export$8c6ed5c666ac1360 : node;
      p(() => {
        window[Symbol.for("radix-ui")] = true;
      }, []);
      return /* @__PURE__ */ y$1(Comp, _extends({}, primitiveProps, {
        ref: forwardedRef
      }));
    });
    Node.displayName = `Primitive.${node}`;
    return {
      ...primitive,
      [node]: Node
    };
  }, {});
  function $8927f6f2acc4f386$export$6d1a0317bde7de7f(target, event) {
    if (target)
      pn(
        () => target.dispatchEvent(event)
      );
  }
  const $e698a72e93240346$var$CHECKBOX_NAME = "Checkbox";
  const [$e698a72e93240346$var$createCheckboxContext, $e698a72e93240346$export$b566c4ff5488ea01] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($e698a72e93240346$var$CHECKBOX_NAME);
  const [$e698a72e93240346$var$CheckboxProvider, $e698a72e93240346$var$useCheckboxContext] = $e698a72e93240346$var$createCheckboxContext($e698a72e93240346$var$CHECKBOX_NAME);
  const $e698a72e93240346$export$48513f6b9f8ce62d = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeCheckbox, name: name2, checked: checkedProp, defaultChecked, required, disabled, value = "on", onCheckedChange, ...checkboxProps } = props;
    const [button, setButton] = h(null);
    const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(
      forwardedRef,
      (node) => setButton(node)
    );
    const hasConsumerStoppedPropagationRef = _$2(false);
    const isFormControl = button ? Boolean(button.closest("form")) : true;
    const [checked = false, setChecked] = $71cd76cc60e0454e$export$6f32135080cb4c3({
      prop: checkedProp,
      defaultProp: defaultChecked,
      onChange: onCheckedChange
    });
    const initialCheckedStateRef = _$2(checked);
    p(() => {
      const form = button === null || button === void 0 ? void 0 : button.form;
      if (form) {
        const reset = () => setChecked(initialCheckedStateRef.current);
        form.addEventListener("reset", reset);
        return () => form.removeEventListener("reset", reset);
      }
    }, [
      button,
      setChecked
    ]);
    return /* @__PURE__ */ y$1($e698a72e93240346$var$CheckboxProvider, {
      scope: __scopeCheckbox,
      state: checked,
      disabled
    }, /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.button, _extends({
      type: "button",
      role: "checkbox",
      "aria-checked": $e698a72e93240346$var$isIndeterminate(checked) ? "mixed" : checked,
      "aria-required": required,
      "data-state": $e698a72e93240346$var$getState(checked),
      "data-disabled": disabled ? "" : void 0,
      disabled,
      value
    }, checkboxProps, {
      ref: composedRefs,
      onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onKeyDown, (event) => {
        if (event.key === "Enter")
          event.preventDefault();
      }),
      onClick: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onClick, (event) => {
        setChecked(
          (prevChecked) => $e698a72e93240346$var$isIndeterminate(prevChecked) ? true : !prevChecked
        );
        if (isFormControl) {
          hasConsumerStoppedPropagationRef.current = event.isPropagationStopped();
          if (!hasConsumerStoppedPropagationRef.current)
            event.stopPropagation();
        }
      })
    })), isFormControl && /* @__PURE__ */ y$1($e698a72e93240346$var$BubbleInput, {
      control: button,
      bubbles: !hasConsumerStoppedPropagationRef.current,
      name: name2,
      value,
      checked,
      required,
      disabled,
      style: {
        transform: "translateX(-100%)"
      }
    }));
  });
  const $e698a72e93240346$var$INDICATOR_NAME = "CheckboxIndicator";
  const $e698a72e93240346$export$59aad738f51d1c05 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeCheckbox, forceMount, ...indicatorProps } = props;
    const context = $e698a72e93240346$var$useCheckboxContext($e698a72e93240346$var$INDICATOR_NAME, __scopeCheckbox);
    return /* @__PURE__ */ y$1($921a889cee6df7e8$export$99c2b779aa4e8b8b, {
      present: forceMount || $e698a72e93240346$var$isIndeterminate(context.state) || context.state === true
    }, /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.span, _extends({
      "data-state": $e698a72e93240346$var$getState(context.state),
      "data-disabled": context.disabled ? "" : void 0
    }, indicatorProps, {
      ref: forwardedRef,
      style: {
        pointerEvents: "none",
        ...props.style
      }
    })));
  });
  const $e698a72e93240346$var$BubbleInput = (props) => {
    const { control, checked, bubbles = true, ...inputProps } = props;
    const ref2 = _$2(null);
    const prevChecked = $010c2913dbd2fe3d$export$5cae361ad82dce8b(checked);
    const controlSize = $db6c3485150b8e66$export$1ab7ae714698c4b8(control);
    p(() => {
      const input = ref2.current;
      const inputProto = window.HTMLInputElement.prototype;
      const descriptor = Object.getOwnPropertyDescriptor(inputProto, "checked");
      const setChecked = descriptor.set;
      if (prevChecked !== checked && setChecked) {
        const event = new Event("click", {
          bubbles
        });
        input.indeterminate = $e698a72e93240346$var$isIndeterminate(checked);
        setChecked.call(input, $e698a72e93240346$var$isIndeterminate(checked) ? false : checked);
        input.dispatchEvent(event);
      }
    }, [
      prevChecked,
      checked,
      bubbles
    ]);
    return /* @__PURE__ */ y$1("input", _extends({
      type: "checkbox",
      "aria-hidden": true,
      defaultChecked: $e698a72e93240346$var$isIndeterminate(checked) ? false : checked
    }, inputProps, {
      tabIndex: -1,
      ref: ref2,
      style: {
        ...props.style,
        ...controlSize,
        position: "absolute",
        pointerEvents: "none",
        opacity: 0,
        margin: 0
      }
    }));
  };
  function $e698a72e93240346$var$isIndeterminate(checked) {
    return checked === "indeterminate";
  }
  function $e698a72e93240346$var$getState(checked) {
    return $e698a72e93240346$var$isIndeterminate(checked) ? "indeterminate" : checked ? "checked" : "unchecked";
  }
  const $e698a72e93240346$export$be92b6f5f03c0fe9 = $e698a72e93240346$export$48513f6b9f8ce62d;
  const $e698a72e93240346$export$adb584737d712b70 = $e698a72e93240346$export$59aad738f51d1c05;
  function _objectWithoutPropertiesLoose(source, excluded) {
    if (source == null)
      return {};
    var target = {};
    var sourceKeys = Object.keys(source);
    var key, i2;
    for (i2 = 0; i2 < sourceKeys.length; i2++) {
      key = sourceKeys[i2];
      if (excluded.indexOf(key) >= 0)
        continue;
      target[key] = source[key];
    }
    return target;
  }
  var _excluded$r = ["color"];
  var BookmarkIcon = /* @__PURE__ */ k(function(_ref, forwardedRef) {
    var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$r);
    return y$1("svg", Object.assign({
      width: "15",
      height: "15",
      viewBox: "0 0 15 15",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    }, props, {
      ref: forwardedRef
    }), y$1("path", {
      d: "M3 2.5C3 2.22386 3.22386 2 3.5 2H11.5C11.7761 2 12 2.22386 12 2.5V13.5C12 13.6818 11.9014 13.8492 11.7424 13.9373C11.5834 14.0254 11.3891 14.0203 11.235 13.924L7.5 11.5896L3.765 13.924C3.61087 14.0203 3.41659 14.0254 3.25762 13.9373C3.09864 13.8492 3 13.6818 3 13.5V2.5ZM4 3V12.5979L6.97 10.7416C7.29427 10.539 7.70573 10.539 8.03 10.7416L11 12.5979V3H4Z",
      fill: color,
      fillRule: "evenodd",
      clipRule: "evenodd"
    }));
  });
  var _excluded$s = ["color"];
  var BookmarkFilledIcon = /* @__PURE__ */ k(function(_ref, forwardedRef) {
    var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$s);
    return y$1("svg", Object.assign({
      width: "15",
      height: "15",
      viewBox: "0 0 15 15",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    }, props, {
      ref: forwardedRef
    }), y$1("path", {
      d: "M3.5 2C3.22386 2 3 2.22386 3 2.5V13.5C3 13.6818 3.09864 13.8492 3.25762 13.9373C3.41659 14.0254 3.61087 14.0203 3.765 13.924L7.5 11.5896L11.235 13.924C11.3891 14.0203 11.5834 14.0254 11.7424 13.9373C11.9014 13.8492 12 13.6818 12 13.5V2.5C12 2.22386 11.7761 2 11.5 2H3.5Z",
      fill: color,
      fillRule: "evenodd",
      clipRule: "evenodd"
    }));
  });
  var _excluded$T = ["color"];
  var CheckIcon = /* @__PURE__ */ k(function(_ref, forwardedRef) {
    var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$T);
    return y$1("svg", Object.assign({
      width: "15",
      height: "15",
      viewBox: "0 0 15 15",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    }, props, {
      ref: forwardedRef
    }), y$1("path", {
      d: "M11.4669 3.72684C11.7558 3.91574 11.8369 4.30308 11.648 4.59198L7.39799 11.092C7.29783 11.2452 7.13556 11.3467 6.95402 11.3699C6.77247 11.3931 6.58989 11.3355 6.45446 11.2124L3.70446 8.71241C3.44905 8.48022 3.43023 8.08494 3.66242 7.82953C3.89461 7.57412 4.28989 7.55529 4.5453 7.78749L6.75292 9.79441L10.6018 3.90792C10.7907 3.61902 11.178 3.53795 11.4669 3.72684Z",
      fill: color,
      fillRule: "evenodd",
      clipRule: "evenodd"
    }));
  });
  var _excluded$1r = ["color"];
  var Cross2Icon = /* @__PURE__ */ k(function(_ref, forwardedRef) {
    var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$1r);
    return y$1("svg", Object.assign({
      width: "15",
      height: "15",
      viewBox: "0 0 15 15",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    }, props, {
      ref: forwardedRef
    }), y$1("path", {
      d: "M11.7816 4.03157C12.0062 3.80702 12.0062 3.44295 11.7816 3.2184C11.5571 2.99385 11.193 2.99385 10.9685 3.2184L7.50005 6.68682L4.03164 3.2184C3.80708 2.99385 3.44301 2.99385 3.21846 3.2184C2.99391 3.44295 2.99391 3.80702 3.21846 4.03157L6.68688 7.49999L3.21846 10.9684C2.99391 11.193 2.99391 11.557 3.21846 11.7816C3.44301 12.0061 3.80708 12.0061 4.03164 11.7816L7.50005 8.31316L10.9685 11.7816C11.193 12.0061 11.5571 12.0061 11.7816 11.7816C12.0062 11.557 12.0062 11.193 11.7816 10.9684L8.31322 7.49999L11.7816 4.03157Z",
      fill: color,
      fillRule: "evenodd",
      clipRule: "evenodd"
    }));
  });
  var _excluded$1s = ["color"];
  var CrossCircledIcon = /* @__PURE__ */ k(function(_ref, forwardedRef) {
    var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$1s);
    return y$1("svg", Object.assign({
      width: "15",
      height: "15",
      viewBox: "0 0 15 15",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    }, props, {
      ref: forwardedRef
    }), y$1("path", {
      d: "M0.877075 7.49988C0.877075 3.84219 3.84222 0.877045 7.49991 0.877045C11.1576 0.877045 14.1227 3.84219 14.1227 7.49988C14.1227 11.1575 11.1576 14.1227 7.49991 14.1227C3.84222 14.1227 0.877075 11.1575 0.877075 7.49988ZM7.49991 1.82704C4.36689 1.82704 1.82708 4.36686 1.82708 7.49988C1.82708 10.6329 4.36689 13.1727 7.49991 13.1727C10.6329 13.1727 13.1727 10.6329 13.1727 7.49988C13.1727 4.36686 10.6329 1.82704 7.49991 1.82704ZM9.85358 5.14644C10.0488 5.3417 10.0488 5.65829 9.85358 5.85355L8.20713 7.49999L9.85358 9.14644C10.0488 9.3417 10.0488 9.65829 9.85358 9.85355C9.65832 10.0488 9.34173 10.0488 9.14647 9.85355L7.50002 8.2071L5.85358 9.85355C5.65832 10.0488 5.34173 10.0488 5.14647 9.85355C4.95121 9.65829 4.95121 9.3417 5.14647 9.14644L6.79292 7.49999L5.14647 5.85355C4.95121 5.65829 4.95121 5.3417 5.14647 5.14644C5.34173 4.95118 5.65832 4.95118 5.85358 5.14644L7.50002 6.79289L9.14647 5.14644C9.34173 4.95118 9.65832 4.95118 9.85358 5.14644Z",
      fill: color,
      fillRule: "evenodd",
      clipRule: "evenodd"
    }));
  });
  var _excluded$1P = ["color"];
  var DownloadIcon = /* @__PURE__ */ k(function(_ref, forwardedRef) {
    var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$1P);
    return y$1("svg", Object.assign({
      width: "15",
      height: "15",
      viewBox: "0 0 15 15",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    }, props, {
      ref: forwardedRef
    }), y$1("path", {
      d: "M7.50005 1.04999C7.74858 1.04999 7.95005 1.25146 7.95005 1.49999V8.41359L10.1819 6.18179C10.3576 6.00605 10.6425 6.00605 10.8182 6.18179C10.994 6.35753 10.994 6.64245 10.8182 6.81819L7.81825 9.81819C7.64251 9.99392 7.35759 9.99392 7.18185 9.81819L4.18185 6.81819C4.00611 6.64245 4.00611 6.35753 4.18185 6.18179C4.35759 6.00605 4.64251 6.00605 4.81825 6.18179L7.05005 8.41359V1.49999C7.05005 1.25146 7.25152 1.04999 7.50005 1.04999ZM2.5 10C2.77614 10 3 10.2239 3 10.5V12C3 12.5539 3.44565 13 3.99635 13H11.0012C11.5529 13 12 12.5528 12 12V10.5C12 10.2239 12.2239 10 12.5 10C12.7761 10 13 10.2239 13 10.5V12C13 13.1041 12.1062 14 11.0012 14H3.99635C2.89019 14 2 13.103 2 12V10.5C2 10.2239 2.22386 10 2.5 10Z",
      fill: color,
      fillRule: "evenodd",
      clipRule: "evenodd"
    }));
  });
  var _excluded$1R = ["color"];
  var DragHandleDots2Icon = /* @__PURE__ */ k(function(_ref, forwardedRef) {
    var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$1R);
    return y$1("svg", Object.assign({
      width: "15",
      height: "15",
      viewBox: "0 0 15 15",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    }, props, {
      ref: forwardedRef
    }), y$1("path", {
      d: "M5.5 4.625C6.12132 4.625 6.625 4.12132 6.625 3.5C6.625 2.87868 6.12132 2.375 5.5 2.375C4.87868 2.375 4.375 2.87868 4.375 3.5C4.375 4.12132 4.87868 4.625 5.5 4.625ZM9.5 4.625C10.1213 4.625 10.625 4.12132 10.625 3.5C10.625 2.87868 10.1213 2.375 9.5 2.375C8.87868 2.375 8.375 2.87868 8.375 3.5C8.375 4.12132 8.87868 4.625 9.5 4.625ZM10.625 7.5C10.625 8.12132 10.1213 8.625 9.5 8.625C8.87868 8.625 8.375 8.12132 8.375 7.5C8.375 6.87868 8.87868 6.375 9.5 6.375C10.1213 6.375 10.625 6.87868 10.625 7.5ZM5.5 8.625C6.12132 8.625 6.625 8.12132 6.625 7.5C6.625 6.87868 6.12132 6.375 5.5 6.375C4.87868 6.375 4.375 6.87868 4.375 7.5C4.375 8.12132 4.87868 8.625 5.5 8.625ZM10.625 11.5C10.625 12.1213 10.1213 12.625 9.5 12.625C8.87868 12.625 8.375 12.1213 8.375 11.5C8.375 10.8787 8.87868 10.375 9.5 10.375C10.1213 10.375 10.625 10.8787 10.625 11.5ZM5.5 12.625C6.12132 12.625 6.625 12.1213 6.625 11.5C6.625 10.8787 6.12132 10.375 5.5 10.375C4.87868 10.375 4.375 10.8787 4.375 11.5C4.375 12.1213 4.87868 12.625 5.5 12.625Z",
      fill: color,
      fillRule: "evenodd",
      clipRule: "evenodd"
    }));
  });
  var _excluded$1W = ["color"];
  var DropdownMenuIcon = /* @__PURE__ */ k(function(_ref, forwardedRef) {
    var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$1W);
    return y$1("svg", Object.assign({
      width: "15",
      height: "15",
      viewBox: "0 0 15 15",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    }, props, {
      ref: forwardedRef
    }), y$1("path", {
      d: "M7.49999 3.09998C7.27907 3.09998 7.09999 3.27906 7.09999 3.49998C7.09999 3.72089 7.27907 3.89998 7.49999 3.89998H14.5C14.7209 3.89998 14.9 3.72089 14.9 3.49998C14.9 3.27906 14.7209 3.09998 14.5 3.09998H7.49999ZM7.49998 5.1C7.27907 5.1 7.09998 5.27908 7.09998 5.5C7.09998 5.72091 7.27907 5.9 7.49998 5.9H14.5C14.7209 5.9 14.9 5.72091 14.9 5.5C14.9 5.27908 14.7209 5.1 14.5 5.1H7.49998ZM7.1 7.5C7.1 7.27908 7.27909 7.1 7.5 7.1H14.5C14.7209 7.1 14.9 7.27908 14.9 7.5C14.9 7.72091 14.7209 7.9 14.5 7.9H7.5C7.27909 7.9 7.1 7.72091 7.1 7.5ZM7.49998 9.1C7.27907 9.1 7.09998 9.27908 7.09998 9.5C7.09998 9.72091 7.27907 9.9 7.49998 9.9H14.5C14.7209 9.9 14.9 9.72091 14.9 9.5C14.9 9.27908 14.7209 9.1 14.5 9.1H7.49998ZM7.09998 11.5C7.09998 11.2791 7.27907 11.1 7.49998 11.1H14.5C14.7209 11.1 14.9 11.2791 14.9 11.5C14.9 11.7209 14.7209 11.9 14.5 11.9H7.49998C7.27907 11.9 7.09998 11.7209 7.09998 11.5ZM2.5 9.25003L5 6.00003H0L2.5 9.25003Z",
      fill: color,
      fillRule: "evenodd",
      clipRule: "evenodd"
    }));
  });
  var _excluded$23 = ["color"];
  var ExternalLinkIcon = /* @__PURE__ */ k(function(_ref, forwardedRef) {
    var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$23);
    return y$1("svg", Object.assign({
      width: "15",
      height: "15",
      viewBox: "0 0 15 15",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    }, props, {
      ref: forwardedRef
    }), y$1("path", {
      d: "M3 2C2.44772 2 2 2.44772 2 3V12C2 12.5523 2.44772 13 3 13H12C12.5523 13 13 12.5523 13 12V8.5C13 8.22386 12.7761 8 12.5 8C12.2239 8 12 8.22386 12 8.5V12H3V3L6.5 3C6.77614 3 7 2.77614 7 2.5C7 2.22386 6.77614 2 6.5 2H3ZM12.8536 2.14645C12.9015 2.19439 12.9377 2.24964 12.9621 2.30861C12.9861 2.36669 12.9996 2.4303 13 2.497L13 2.5V2.50049V5.5C13 5.77614 12.7761 6 12.5 6C12.2239 6 12 5.77614 12 5.5V3.70711L6.85355 8.85355C6.65829 9.04882 6.34171 9.04882 6.14645 8.85355C5.95118 8.65829 5.95118 8.34171 6.14645 8.14645L11.2929 3H9.5C9.22386 3 9 2.77614 9 2.5C9 2.22386 9.22386 2 9.5 2H12.4999H12.5C12.5678 2 12.6324 2.01349 12.6914 2.03794C12.7504 2.06234 12.8056 2.09851 12.8536 2.14645Z",
      fill: color,
      fillRule: "evenodd",
      clipRule: "evenodd"
    }));
  });
  var _excluded$2b = ["color"];
  var FilePlusIcon = /* @__PURE__ */ k(function(_ref, forwardedRef) {
    var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$2b);
    return y$1("svg", Object.assign({
      width: "15",
      height: "15",
      viewBox: "0 0 15 15",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    }, props, {
      ref: forwardedRef
    }), y$1("path", {
      d: "M3.5 2C3.22386 2 3 2.22386 3 2.5V12.5C3 12.7761 3.22386 13 3.5 13H11.5C11.7761 13 12 12.7761 12 12.5V4.70711L9.29289 2H3.5ZM2 2.5C2 1.67157 2.67157 1 3.5 1H9.5C9.63261 1 9.75979 1.05268 9.85355 1.14645L12.7803 4.07322C12.921 4.21388 13 4.40464 13 4.60355V12.5C13 13.3284 12.3284 14 11.5 14H3.5C2.67157 14 2 13.3284 2 12.5V2.5ZM4.75 7.5C4.75 7.22386 4.97386 7 5.25 7H7V5.25C7 4.97386 7.22386 4.75 7.5 4.75C7.77614 4.75 8 4.97386 8 5.25V7H9.75C10.0261 7 10.25 7.22386 10.25 7.5C10.25 7.77614 10.0261 8 9.75 8H8V9.75C8 10.0261 7.77614 10.25 7.5 10.25C7.22386 10.25 7 10.0261 7 9.75V8H5.25C4.97386 8 4.75 7.77614 4.75 7.5Z",
      fill: color,
      fillRule: "evenodd",
      clipRule: "evenodd"
    }));
  });
  var _excluded$2l = ["color"];
  var GearIcon = /* @__PURE__ */ k(function(_ref, forwardedRef) {
    var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$2l);
    return y$1("svg", Object.assign({
      width: "15",
      height: "15",
      viewBox: "0 0 15 15",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    }, props, {
      ref: forwardedRef
    }), y$1("path", {
      d: "M7.07095 0.650238C6.67391 0.650238 6.32977 0.925096 6.24198 1.31231L6.0039 2.36247C5.6249 2.47269 5.26335 2.62363 4.92436 2.81013L4.01335 2.23585C3.67748 2.02413 3.23978 2.07312 2.95903 2.35386L2.35294 2.95996C2.0722 3.2407 2.0232 3.6784 2.23493 4.01427L2.80942 4.92561C2.62307 5.2645 2.47227 5.62594 2.36216 6.00481L1.31209 6.24287C0.924883 6.33065 0.650024 6.6748 0.650024 7.07183V7.92897C0.650024 8.32601 0.924883 8.67015 1.31209 8.75794L2.36228 8.99603C2.47246 9.375 2.62335 9.73652 2.80979 10.0755L2.2354 10.9867C2.02367 11.3225 2.07267 11.7602 2.35341 12.041L2.95951 12.6471C3.24025 12.9278 3.67795 12.9768 4.01382 12.7651L4.92506 12.1907C5.26384 12.377 5.62516 12.5278 6.0039 12.6379L6.24198 13.6881C6.32977 14.0753 6.67391 14.3502 7.07095 14.3502H7.92809C8.32512 14.3502 8.66927 14.0753 8.75705 13.6881L8.99505 12.6383C9.37411 12.5282 9.73573 12.3773 10.0748 12.1909L10.986 12.7653C11.3218 12.977 11.7595 12.928 12.0403 12.6473L12.6464 12.0412C12.9271 11.7604 12.9761 11.3227 12.7644 10.9869L12.1902 10.076C12.3768 9.73688 12.5278 9.37515 12.638 8.99596L13.6879 8.75794C14.0751 8.67015 14.35 8.32601 14.35 7.92897V7.07183C14.35 6.6748 14.0751 6.33065 13.6879 6.24287L12.6381 6.00488C12.528 5.62578 12.3771 5.26414 12.1906 4.92507L12.7648 4.01407C12.9766 3.6782 12.9276 3.2405 12.6468 2.95975L12.0407 2.35366C11.76 2.07292 11.3223 2.02392 10.9864 2.23565L10.0755 2.80989C9.73622 2.62328 9.37437 2.47229 8.99505 2.36209L8.75705 1.31231C8.66927 0.925096 8.32512 0.650238 7.92809 0.650238H7.07095ZM4.92053 3.81251C5.44724 3.44339 6.05665 3.18424 6.71543 3.06839L7.07095 1.50024H7.92809L8.28355 3.06816C8.94267 3.18387 9.5524 3.44302 10.0794 3.81224L11.4397 2.9547L12.0458 3.56079L11.1882 4.92117C11.5573 5.44798 11.8164 6.0575 11.9321 6.71638L13.5 7.07183V7.92897L11.932 8.28444C11.8162 8.94342 11.557 9.55301 11.1878 10.0798L12.0453 11.4402L11.4392 12.0462L10.0787 11.1886C9.55192 11.5576 8.94241 11.8166 8.28355 11.9323L7.92809 13.5002H7.07095L6.71543 11.932C6.0569 11.8162 5.44772 11.5572 4.92116 11.1883L3.56055 12.046L2.95445 11.4399L3.81213 10.0794C3.4431 9.55266 3.18403 8.94326 3.06825 8.2845L1.50002 7.92897V7.07183L3.06818 6.71632C3.18388 6.05765 3.44283 5.44833 3.81171 4.92165L2.95398 3.561L3.56008 2.95491L4.92053 3.81251ZM9.02496 7.50008C9.02496 8.34226 8.34223 9.02499 7.50005 9.02499C6.65786 9.02499 5.97513 8.34226 5.97513 7.50008C5.97513 6.65789 6.65786 5.97516 7.50005 5.97516C8.34223 5.97516 9.02496 6.65789 9.02496 7.50008ZM9.92496 7.50008C9.92496 8.83932 8.83929 9.92499 7.50005 9.92499C6.1608 9.92499 5.07513 8.83932 5.07513 7.50008C5.07513 6.16084 6.1608 5.07516 7.50005 5.07516C8.83929 5.07516 9.92496 6.16084 9.92496 7.50008Z",
      fill: color,
      fillRule: "evenodd",
      clipRule: "evenodd"
    }));
  });
  var _excluded$3o = ["color"];
  var Pencil2Icon = /* @__PURE__ */ k(function(_ref, forwardedRef) {
    var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$3o);
    return y$1("svg", Object.assign({
      width: "15",
      height: "15",
      viewBox: "0 0 15 15",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    }, props, {
      ref: forwardedRef
    }), y$1("path", {
      d: "M12.1464 1.14645C12.3417 0.951184 12.6583 0.951184 12.8535 1.14645L14.8535 3.14645C15.0488 3.34171 15.0488 3.65829 14.8535 3.85355L10.9109 7.79618C10.8349 7.87218 10.7471 7.93543 10.651 7.9835L6.72359 9.94721C6.53109 10.0435 6.29861 10.0057 6.14643 9.85355C5.99425 9.70137 5.95652 9.46889 6.05277 9.27639L8.01648 5.34897C8.06455 5.25283 8.1278 5.16507 8.2038 5.08907L12.1464 1.14645ZM12.5 2.20711L8.91091 5.79618L7.87266 7.87267L8.12731 8.12732L10.2038 7.08907L13.7929 3.5L12.5 2.20711ZM9.99998 2L8.99998 3H4.9C4.47171 3 4.18056 3.00039 3.95552 3.01877C3.73631 3.03668 3.62421 3.06915 3.54601 3.10899C3.35785 3.20487 3.20487 3.35785 3.10899 3.54601C3.06915 3.62421 3.03669 3.73631 3.01878 3.95552C3.00039 4.18056 3 4.47171 3 4.9V11.1C3 11.5283 3.00039 11.8194 3.01878 12.0445C3.03669 12.2637 3.06915 12.3758 3.10899 12.454C3.20487 12.6422 3.35785 12.7951 3.54601 12.891C3.62421 12.9309 3.73631 12.9633 3.95552 12.9812C4.18056 12.9996 4.47171 13 4.9 13H11.1C11.5283 13 11.8194 12.9996 12.0445 12.9812C12.2637 12.9633 12.3758 12.9309 12.454 12.891C12.6422 12.7951 12.7951 12.6422 12.891 12.454C12.9309 12.3758 12.9633 12.2637 12.9812 12.0445C12.9996 11.8194 13 11.5283 13 11.1V6.99998L14 5.99998V11.1V11.1207C14 11.5231 14 11.8553 13.9779 12.1259C13.9549 12.407 13.9057 12.6653 13.782 12.908C13.5903 13.2843 13.2843 13.5903 12.908 13.782C12.6653 13.9057 12.407 13.9549 12.1259 13.9779C11.8553 14 11.5231 14 11.1207 14H11.1H4.9H4.87934C4.47686 14 4.14468 14 3.87409 13.9779C3.59304 13.9549 3.33469 13.9057 3.09202 13.782C2.7157 13.5903 2.40973 13.2843 2.21799 12.908C2.09434 12.6653 2.04506 12.407 2.0221 12.1259C1.99999 11.8553 1.99999 11.5231 2 11.1207V11.1206V11.1V4.9V4.87935V4.87932V4.87931C1.99999 4.47685 1.99999 4.14468 2.0221 3.87409C2.04506 3.59304 2.09434 3.33469 2.21799 3.09202C2.40973 2.71569 2.7157 2.40973 3.09202 2.21799C3.33469 2.09434 3.59304 2.04506 3.87409 2.0221C4.14468 1.99999 4.47685 1.99999 4.87932 2H4.87935H4.9H9.99998Z",
      fill: color,
      fillRule: "evenodd",
      clipRule: "evenodd"
    }));
  });
  var _excluded$4N = ["color"];
  var UpdateIcon = /* @__PURE__ */ k(function(_ref, forwardedRef) {
    var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$4N);
    return y$1("svg", Object.assign({
      width: "15",
      height: "15",
      viewBox: "0 0 15 15",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    }, props, {
      ref: forwardedRef
    }), y$1("path", {
      d: "M1.90321 7.29677C1.90321 10.341 4.11041 12.4147 6.58893 12.8439C6.87255 12.893 7.06266 13.1627 7.01355 13.4464C6.96444 13.73 6.69471 13.9201 6.41109 13.871C3.49942 13.3668 0.86084 10.9127 0.86084 7.29677C0.860839 5.76009 1.55996 4.55245 2.37639 3.63377C2.96124 2.97568 3.63034 2.44135 4.16846 2.03202L2.53205 2.03202C2.25591 2.03202 2.03205 1.80816 2.03205 1.53202C2.03205 1.25588 2.25591 1.03202 2.53205 1.03202L5.53205 1.03202C5.80819 1.03202 6.03205 1.25588 6.03205 1.53202L6.03205 4.53202C6.03205 4.80816 5.80819 5.03202 5.53205 5.03202C5.25591 5.03202 5.03205 4.80816 5.03205 4.53202L5.03205 2.68645L5.03054 2.68759L5.03045 2.68766L5.03044 2.68767L5.03043 2.68767C4.45896 3.11868 3.76059 3.64538 3.15554 4.3262C2.44102 5.13021 1.90321 6.10154 1.90321 7.29677ZM13.0109 7.70321C13.0109 4.69115 10.8505 2.6296 8.40384 2.17029C8.12093 2.11718 7.93465 1.84479 7.98776 1.56188C8.04087 1.27898 8.31326 1.0927 8.59616 1.14581C11.4704 1.68541 14.0532 4.12605 14.0532 7.70321C14.0532 9.23988 13.3541 10.4475 12.5377 11.3662C11.9528 12.0243 11.2837 12.5586 10.7456 12.968L12.3821 12.968C12.6582 12.968 12.8821 13.1918 12.8821 13.468C12.8821 13.7441 12.6582 13.968 12.3821 13.968L9.38205 13.968C9.10591 13.968 8.88205 13.7441 8.88205 13.468L8.88205 10.468C8.88205 10.1918 9.10591 9.96796 9.38205 9.96796C9.65819 9.96796 9.88205 10.1918 9.88205 10.468L9.88205 12.3135L9.88362 12.3123C10.4551 11.8813 11.1535 11.3546 11.7585 10.6738C12.4731 9.86976 13.0109 8.89844 13.0109 7.70321Z",
      fill: color,
      fillRule: "evenodd",
      clipRule: "evenodd"
    }));
  });
  var _excluded$4O = ["color"];
  var UploadIcon = /* @__PURE__ */ k(function(_ref, forwardedRef) {
    var _ref$color = _ref.color, color = _ref$color === void 0 ? "currentColor" : _ref$color, props = _objectWithoutPropertiesLoose(_ref, _excluded$4O);
    return y$1("svg", Object.assign({
      width: "15",
      height: "15",
      viewBox: "0 0 15 15",
      fill: "none",
      xmlns: "http://www.w3.org/2000/svg"
    }, props, {
      ref: forwardedRef
    }), y$1("path", {
      d: "M7.81825 1.18188C7.64251 1.00615 7.35759 1.00615 7.18185 1.18188L4.18185 4.18188C4.00611 4.35762 4.00611 4.64254 4.18185 4.81828C4.35759 4.99401 4.64251 4.99401 4.81825 4.81828L7.05005 2.58648V9.49996C7.05005 9.74849 7.25152 9.94996 7.50005 9.94996C7.74858 9.94996 7.95005 9.74849 7.95005 9.49996V2.58648L10.1819 4.81828C10.3576 4.99401 10.6425 4.99401 10.8182 4.81828C10.994 4.64254 10.994 4.35762 10.8182 4.18188L7.81825 1.18188ZM2.5 9.99997C2.77614 9.99997 3 10.2238 3 10.5V12C3 12.5538 3.44565 13 3.99635 13H11.0012C11.5529 13 12 12.5528 12 12V10.5C12 10.2238 12.2239 9.99997 12.5 9.99997C12.7761 9.99997 13 10.2238 13 10.5V12C13 13.104 12.1062 14 11.0012 14H3.99635C2.89019 14 2 13.103 2 12V10.5C2 10.2238 2.22386 9.99997 2.5 9.99997Z",
      fill: color,
      fillRule: "evenodd",
      clipRule: "evenodd"
    }));
  });
  var _$1 = 0;
  function o(o2, e2, n2, t2, f2, l2) {
    var s2, u2, a2 = {};
    for (u2 in e2)
      "ref" == u2 ? s2 = e2[u2] : a2[u2] = e2[u2];
    var i2 = { type: o2, props: a2, key: n2, ref: s2, __k: null, __: null, __b: 0, __e: null, __d: void 0, __c: null, __h: null, constructor: void 0, __v: --_$1, __source: f2, __self: l2 };
    if ("function" == typeof o2 && (s2 = o2.defaultProps))
      for (u2 in s2)
        void 0 === a2[u2] && (a2[u2] = s2[u2]);
    return l$1.vnode && l$1.vnode(i2), i2;
  }
  const RadixCheckbox = (props) => o("form", {
    className: "CheckboxForm",
    children: [o("label", {
      className: "Label",
      htmlFor: props.id,
      children: props.label
    }), o("div", {
      style: {
        display: "flex",
        alignItems: "center"
      },
      children: o($e698a72e93240346$export$be92b6f5f03c0fe9, {
        className: "CheckboxRoot",
        checked: props.checked,
        id: props.id,
        onCheckedChange: (checked) => {
          props.onChangeCallback(checked, {
            elementID: props.id,
            exerciseID: props.exerciseID,
            sectionID: props.sectionID,
            exerciseTitle: props.exerciseTitle,
            sectionTitle: props.sectionTitle
          });
        },
        children: o($e698a72e93240346$export$adb584737d712b70, {
          className: "CheckboxIndicator",
          children: o(CheckIcon, {})
        })
      })
    })]
  });
  const WordalistExerciseSectionCheckbox = (props) => {
    const sectionSelectionContext = q$1(SectionSelectionContext);
    return o("div", {
      class: ELEM_PAGE_EXERCISE_SECTIONS_ADDITION_BASE_ID,
      children: o(RadixCheckbox, {
        id: props.id,
        exerciseID: props.exerciseID,
        sectionID: props.sectionID,
        exerciseTitle: props.exerciseTitle,
        sectionTitle: props.sectionTitle,
        label: instance.t(`${LANG_NS_MAIN}:pageExercisePracticeSelectionLabel`),
        checked: sectionSelectionContext.selectedSections.filter(({
          sectionID
        }) => sectionID === props.sectionID).length > 0,
        onChangeCallback: (checked, {
          elementID,
          exerciseID,
          sectionID,
          exerciseTitle,
          sectionTitle
        }) => {
          if (checked && exerciseID.length > 0 && sectionSelectionContext.selectedExercise.exerciseID.length === 0 || checked && exerciseID.length > 0 && sectionSelectionContext.selectedExercise.exerciseID !== exerciseID) {
            sectionSelectionContext.resetAndAddToSelectedSections({
              elementID,
              sectionID,
              sectionTitle
            });
            sectionSelectionContext.setSelectedExercise({
              exerciseID,
              exerciseTitle
            });
          } else if (checked && // Add ID
          sectionSelectionContext.selectedSections.filter(propFilterElementID(elementID)).length === 0) {
            sectionSelectionContext.addToSelectedSections({
              elementID,
              sectionID,
              sectionTitle
            });
          } else if (!checked && sectionSelectionContext.selectedSections.filter(propFilterElementID(elementID)).length > 0) {
            if (sectionSelectionContext.selectedSections.length === 1) {
              sectionSelectionContext.reset();
            } else {
              sectionSelectionContext.removeFromSelectedSections({
                elementID
              });
            }
          }
        }
      })
    });
  };
  function $e02a7d9cb1dc128c$export$c74125a8e3af6bb2(name2) {
    const PROVIDER_NAME = name2 + "CollectionProvider";
    const [createCollectionContext, createCollectionScope] = $c512c27ab02ef895$export$50c7b4e9d9f19c1(PROVIDER_NAME);
    const [CollectionProviderImpl, useCollectionContext] = createCollectionContext(PROVIDER_NAME, {
      collectionRef: {
        current: null
      },
      itemMap: /* @__PURE__ */ new Map()
    });
    const CollectionProvider = (props) => {
      const { scope, children } = props;
      const ref2 = Cn.useRef(null);
      const itemMap = Cn.useRef(/* @__PURE__ */ new Map()).current;
      return /* @__PURE__ */ Cn.createElement(CollectionProviderImpl, {
        scope,
        itemMap,
        collectionRef: ref2
      }, children);
    };
    const COLLECTION_SLOT_NAME = name2 + "CollectionSlot";
    const CollectionSlot = /* @__PURE__ */ Cn.forwardRef((props, forwardedRef) => {
      const { scope, children } = props;
      const context = useCollectionContext(COLLECTION_SLOT_NAME, scope);
      const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, context.collectionRef);
      return /* @__PURE__ */ Cn.createElement($5e63c961fc1ce211$export$8c6ed5c666ac1360, {
        ref: composedRefs
      }, children);
    });
    const ITEM_SLOT_NAME = name2 + "CollectionItemSlot";
    const ITEM_DATA_ATTR = "data-radix-collection-item";
    const CollectionItemSlot = /* @__PURE__ */ Cn.forwardRef((props, forwardedRef) => {
      const { scope, children, ...itemData } = props;
      const ref2 = Cn.useRef(null);
      const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref2);
      const context = useCollectionContext(ITEM_SLOT_NAME, scope);
      Cn.useEffect(() => {
        context.itemMap.set(ref2, {
          ref: ref2,
          ...itemData
        });
        return () => void context.itemMap.delete(ref2);
      });
      return /* @__PURE__ */ Cn.createElement($5e63c961fc1ce211$export$8c6ed5c666ac1360, {
        [ITEM_DATA_ATTR]: "",
        ref: composedRefs
      }, children);
    });
    function useCollection(scope) {
      const context = useCollectionContext(name2 + "CollectionConsumer", scope);
      const getItems = Cn.useCallback(() => {
        const collectionNode = context.collectionRef.current;
        if (!collectionNode)
          return [];
        const orderedNodes = Array.from(collectionNode.querySelectorAll(`[${ITEM_DATA_ATTR}]`));
        const items = Array.from(context.itemMap.values());
        const orderedItems = items.sort(
          (a2, b2) => orderedNodes.indexOf(a2.ref.current) - orderedNodes.indexOf(b2.ref.current)
        );
        return orderedItems;
      }, [
        context.collectionRef,
        context.itemMap
      ]);
      return getItems;
    }
    return [
      {
        Provider: CollectionProvider,
        Slot: CollectionSlot,
        ItemSlot: CollectionItemSlot
      },
      useCollection,
      createCollectionScope
    ];
  }
  const $1746a345f3d73bb7$var$useReactId = $2AODx$react["useId".toString()] || (() => void 0);
  let $1746a345f3d73bb7$var$count = 0;
  function $1746a345f3d73bb7$export$f680877a34711e37(deterministicId) {
    const [id, setId] = h($1746a345f3d73bb7$var$useReactId());
    $9f79659886946c16$export$e5c5a5f917a5871c(() => {
      if (!deterministicId)
        setId(
          (reactId) => reactId !== null && reactId !== void 0 ? reactId : String($1746a345f3d73bb7$var$count++)
        );
    }, [
      deterministicId
    ]);
    return deterministicId || (id ? `radix-${id}` : "");
  }
  const $f631663db3294ace$var$DirectionContext = /* @__PURE__ */ G$1(void 0);
  function $f631663db3294ace$export$b39126d51d94e6f3(localDir) {
    const globalDir = q$1($f631663db3294ace$var$DirectionContext);
    return localDir || globalDir || "ltr";
  }
  const $d7bdfb9eb0fdf311$var$ENTRY_FOCUS = "rovingFocusGroup.onEntryFocus";
  const $d7bdfb9eb0fdf311$var$EVENT_OPTIONS = {
    bubbles: false,
    cancelable: true
  };
  const $d7bdfb9eb0fdf311$var$GROUP_NAME = "RovingFocusGroup";
  const [$d7bdfb9eb0fdf311$var$Collection, $d7bdfb9eb0fdf311$var$useCollection, $d7bdfb9eb0fdf311$var$createCollectionScope] = $e02a7d9cb1dc128c$export$c74125a8e3af6bb2($d7bdfb9eb0fdf311$var$GROUP_NAME);
  const [$d7bdfb9eb0fdf311$var$createRovingFocusGroupContext, $d7bdfb9eb0fdf311$export$c7109489551a4f4] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($d7bdfb9eb0fdf311$var$GROUP_NAME, [
    $d7bdfb9eb0fdf311$var$createCollectionScope
  ]);
  const [$d7bdfb9eb0fdf311$var$RovingFocusProvider, $d7bdfb9eb0fdf311$var$useRovingFocusContext] = $d7bdfb9eb0fdf311$var$createRovingFocusGroupContext($d7bdfb9eb0fdf311$var$GROUP_NAME);
  const $d7bdfb9eb0fdf311$export$8699f7c8af148338 = /* @__PURE__ */ k((props, forwardedRef) => {
    return /* @__PURE__ */ y$1($d7bdfb9eb0fdf311$var$Collection.Provider, {
      scope: props.__scopeRovingFocusGroup
    }, /* @__PURE__ */ y$1($d7bdfb9eb0fdf311$var$Collection.Slot, {
      scope: props.__scopeRovingFocusGroup
    }, /* @__PURE__ */ y$1($d7bdfb9eb0fdf311$var$RovingFocusGroupImpl, _extends({}, props, {
      ref: forwardedRef
    }))));
  });
  const $d7bdfb9eb0fdf311$var$RovingFocusGroupImpl = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeRovingFocusGroup, orientation, loop = false, dir, currentTabStopId: currentTabStopIdProp, defaultCurrentTabStopId, onCurrentTabStopIdChange, onEntryFocus, ...groupProps } = props;
    const ref2 = _$2(null);
    const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref2);
    const direction = $f631663db3294ace$export$b39126d51d94e6f3(dir);
    const [currentTabStopId = null, setCurrentTabStopId] = $71cd76cc60e0454e$export$6f32135080cb4c3({
      prop: currentTabStopIdProp,
      defaultProp: defaultCurrentTabStopId,
      onChange: onCurrentTabStopIdChange
    });
    const [isTabbingBackOut, setIsTabbingBackOut] = h(false);
    const handleEntryFocus = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onEntryFocus);
    const getItems = $d7bdfb9eb0fdf311$var$useCollection(__scopeRovingFocusGroup);
    const isClickFocusRef = _$2(false);
    const [focusableItemsCount, setFocusableItemsCount] = h(0);
    p(() => {
      const node = ref2.current;
      if (node) {
        node.addEventListener($d7bdfb9eb0fdf311$var$ENTRY_FOCUS, handleEntryFocus);
        return () => node.removeEventListener($d7bdfb9eb0fdf311$var$ENTRY_FOCUS, handleEntryFocus);
      }
    }, [
      handleEntryFocus
    ]);
    return /* @__PURE__ */ y$1($d7bdfb9eb0fdf311$var$RovingFocusProvider, {
      scope: __scopeRovingFocusGroup,
      orientation,
      dir: direction,
      loop,
      currentTabStopId,
      onItemFocus: T$1(
        (tabStopId) => setCurrentTabStopId(tabStopId),
        [
          setCurrentTabStopId
        ]
      ),
      onItemShiftTab: T$1(
        () => setIsTabbingBackOut(true),
        []
      ),
      onFocusableItemAdd: T$1(
        () => setFocusableItemsCount(
          (prevCount) => prevCount + 1
        ),
        []
      ),
      onFocusableItemRemove: T$1(
        () => setFocusableItemsCount(
          (prevCount) => prevCount - 1
        ),
        []
      )
    }, /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends({
      tabIndex: isTabbingBackOut || focusableItemsCount === 0 ? -1 : 0,
      "data-orientation": orientation
    }, groupProps, {
      ref: composedRefs,
      style: {
        outline: "none",
        ...props.style
      },
      onMouseDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onMouseDown, () => {
        isClickFocusRef.current = true;
      }),
      onFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onFocus, (event) => {
        const isKeyboardFocus = !isClickFocusRef.current;
        if (event.target === event.currentTarget && isKeyboardFocus && !isTabbingBackOut) {
          const entryFocusEvent = new CustomEvent($d7bdfb9eb0fdf311$var$ENTRY_FOCUS, $d7bdfb9eb0fdf311$var$EVENT_OPTIONS);
          event.currentTarget.dispatchEvent(entryFocusEvent);
          if (!entryFocusEvent.defaultPrevented) {
            const items = getItems().filter(
              (item) => item.focusable
            );
            const activeItem = items.find(
              (item) => item.active
            );
            const currentItem = items.find(
              (item) => item.id === currentTabStopId
            );
            const candidateItems = [
              activeItem,
              currentItem,
              ...items
            ].filter(Boolean);
            const candidateNodes = candidateItems.map(
              (item) => item.ref.current
            );
            $d7bdfb9eb0fdf311$var$focusFirst(candidateNodes);
          }
        }
        isClickFocusRef.current = false;
      }),
      onBlur: $e42e1063c40fb3ef$export$b9ecd428b558ff10(
        props.onBlur,
        () => setIsTabbingBackOut(false)
      )
    })));
  });
  const $d7bdfb9eb0fdf311$var$ITEM_NAME = "RovingFocusGroupItem";
  const $d7bdfb9eb0fdf311$export$ab9df7c53fe8454 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeRovingFocusGroup, focusable = true, active = false, tabStopId, ...itemProps } = props;
    const autoId = $1746a345f3d73bb7$export$f680877a34711e37();
    const id = tabStopId || autoId;
    const context = $d7bdfb9eb0fdf311$var$useRovingFocusContext($d7bdfb9eb0fdf311$var$ITEM_NAME, __scopeRovingFocusGroup);
    const isCurrentTabStop = context.currentTabStopId === id;
    const getItems = $d7bdfb9eb0fdf311$var$useCollection(__scopeRovingFocusGroup);
    const { onFocusableItemAdd, onFocusableItemRemove } = context;
    p(() => {
      if (focusable) {
        onFocusableItemAdd();
        return () => onFocusableItemRemove();
      }
    }, [
      focusable,
      onFocusableItemAdd,
      onFocusableItemRemove
    ]);
    return /* @__PURE__ */ y$1($d7bdfb9eb0fdf311$var$Collection.ItemSlot, {
      scope: __scopeRovingFocusGroup,
      id,
      focusable,
      active
    }, /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.span, _extends({
      tabIndex: isCurrentTabStop ? 0 : -1,
      "data-orientation": context.orientation
    }, itemProps, {
      ref: forwardedRef,
      onMouseDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onMouseDown, (event) => {
        if (!focusable)
          event.preventDefault();
        else
          context.onItemFocus(id);
      }),
      onFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(
        props.onFocus,
        () => context.onItemFocus(id)
      ),
      onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onKeyDown, (event) => {
        if (event.key === "Tab" && event.shiftKey) {
          context.onItemShiftTab();
          return;
        }
        if (event.target !== event.currentTarget)
          return;
        const focusIntent = $d7bdfb9eb0fdf311$var$getFocusIntent(event, context.orientation, context.dir);
        if (focusIntent !== void 0) {
          event.preventDefault();
          const items = getItems().filter(
            (item) => item.focusable
          );
          let candidateNodes = items.map(
            (item) => item.ref.current
          );
          if (focusIntent === "last")
            candidateNodes.reverse();
          else if (focusIntent === "prev" || focusIntent === "next") {
            if (focusIntent === "prev")
              candidateNodes.reverse();
            const currentIndex = candidateNodes.indexOf(event.currentTarget);
            candidateNodes = context.loop ? $d7bdfb9eb0fdf311$var$wrapArray(candidateNodes, currentIndex + 1) : candidateNodes.slice(currentIndex + 1);
          }
          setTimeout(
            () => $d7bdfb9eb0fdf311$var$focusFirst(candidateNodes)
          );
        }
      })
    })));
  });
  const $d7bdfb9eb0fdf311$var$MAP_KEY_TO_FOCUS_INTENT = {
    ArrowLeft: "prev",
    ArrowUp: "prev",
    ArrowRight: "next",
    ArrowDown: "next",
    PageUp: "first",
    Home: "first",
    PageDown: "last",
    End: "last"
  };
  function $d7bdfb9eb0fdf311$var$getDirectionAwareKey(key, dir) {
    if (dir !== "rtl")
      return key;
    return key === "ArrowLeft" ? "ArrowRight" : key === "ArrowRight" ? "ArrowLeft" : key;
  }
  function $d7bdfb9eb0fdf311$var$getFocusIntent(event, orientation, dir) {
    const key = $d7bdfb9eb0fdf311$var$getDirectionAwareKey(event.key, dir);
    if (orientation === "vertical" && [
      "ArrowLeft",
      "ArrowRight"
    ].includes(key))
      return void 0;
    if (orientation === "horizontal" && [
      "ArrowUp",
      "ArrowDown"
    ].includes(key))
      return void 0;
    return $d7bdfb9eb0fdf311$var$MAP_KEY_TO_FOCUS_INTENT[key];
  }
  function $d7bdfb9eb0fdf311$var$focusFirst(candidates) {
    const PREVIOUSLY_FOCUSED_ELEMENT = document.activeElement;
    for (const candidate of candidates) {
      if (candidate === PREVIOUSLY_FOCUSED_ELEMENT)
        return;
      candidate.focus();
      if (document.activeElement !== PREVIOUSLY_FOCUSED_ELEMENT)
        return;
    }
  }
  function $d7bdfb9eb0fdf311$var$wrapArray(array, startIndex) {
    return array.map(
      (_2, index2) => array[(startIndex + index2) % array.length]
    );
  }
  const $d7bdfb9eb0fdf311$export$be92b6f5f03c0fe9 = $d7bdfb9eb0fdf311$export$8699f7c8af148338;
  const $d7bdfb9eb0fdf311$export$6d08773d2e66f8f2 = $d7bdfb9eb0fdf311$export$ab9df7c53fe8454;
  const $6c1fd9e6a8969628$var$TOGGLE_GROUP_NAME = "ToggleGroup";
  const [$6c1fd9e6a8969628$var$createToggleGroupContext, $6c1fd9e6a8969628$export$d1c7c4bcd9f26dd4] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($6c1fd9e6a8969628$var$TOGGLE_GROUP_NAME, [
    $d7bdfb9eb0fdf311$export$c7109489551a4f4
  ]);
  $d7bdfb9eb0fdf311$export$c7109489551a4f4();
  $6c1fd9e6a8969628$var$createToggleGroupContext($6c1fd9e6a8969628$var$TOGGLE_GROUP_NAME);
  $6c1fd9e6a8969628$var$createToggleGroupContext($6c1fd9e6a8969628$var$TOGGLE_GROUP_NAME);
  const $3dc4ded751c8bdfb$var$TOOLBAR_NAME = "Toolbar";
  const [$3dc4ded751c8bdfb$var$createToolbarContext, $3dc4ded751c8bdfb$export$233e637670877d91] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($3dc4ded751c8bdfb$var$TOOLBAR_NAME, [
    $d7bdfb9eb0fdf311$export$c7109489551a4f4,
    $6c1fd9e6a8969628$export$d1c7c4bcd9f26dd4
  ]);
  const $3dc4ded751c8bdfb$var$useRovingFocusGroupScope = $d7bdfb9eb0fdf311$export$c7109489551a4f4();
  $6c1fd9e6a8969628$export$d1c7c4bcd9f26dd4();
  const [$3dc4ded751c8bdfb$var$ToolbarProvider, $3dc4ded751c8bdfb$var$useToolbarContext] = $3dc4ded751c8bdfb$var$createToolbarContext($3dc4ded751c8bdfb$var$TOOLBAR_NAME);
  const $3dc4ded751c8bdfb$export$4c260019440d418f = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeToolbar, orientation = "horizontal", dir, loop = true, ...toolbarProps } = props;
    const rovingFocusGroupScope = $3dc4ded751c8bdfb$var$useRovingFocusGroupScope(__scopeToolbar);
    const direction = $f631663db3294ace$export$b39126d51d94e6f3(dir);
    return /* @__PURE__ */ y$1($3dc4ded751c8bdfb$var$ToolbarProvider, {
      scope: __scopeToolbar,
      orientation,
      dir: direction
    }, /* @__PURE__ */ y$1($d7bdfb9eb0fdf311$export$be92b6f5f03c0fe9, _extends({
      asChild: true
    }, rovingFocusGroupScope, {
      orientation,
      dir: direction,
      loop
    }), /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends({
      role: "toolbar",
      "aria-orientation": orientation,
      dir: direction
    }, toolbarProps, {
      ref: forwardedRef
    }))));
  });
  const $3dc4ded751c8bdfb$export$e5c1a33878e86e9e = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeToolbar, ...buttonProps } = props;
    const rovingFocusGroupScope = $3dc4ded751c8bdfb$var$useRovingFocusGroupScope(__scopeToolbar);
    return /* @__PURE__ */ y$1($d7bdfb9eb0fdf311$export$6d08773d2e66f8f2, _extends({
      asChild: true
    }, rovingFocusGroupScope, {
      focusable: !props.disabled
    }), /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.button, _extends({
      type: "button"
    }, buttonProps, {
      ref: forwardedRef
    })));
  });
  const $3dc4ded751c8bdfb$export$ff5714eba66809fd = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeToolbar, ...linkProps } = props;
    const rovingFocusGroupScope = $3dc4ded751c8bdfb$var$useRovingFocusGroupScope(__scopeToolbar);
    return /* @__PURE__ */ y$1($d7bdfb9eb0fdf311$export$6d08773d2e66f8f2, _extends({
      asChild: true
    }, rovingFocusGroupScope, {
      focusable: true
    }), /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.a, _extends({}, linkProps, {
      ref: forwardedRef,
      onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onKeyDown, (event) => {
        if (event.key === " ")
          event.currentTarget.click();
      })
    })));
  });
  const $3dc4ded751c8bdfb$export$be92b6f5f03c0fe9 = $3dc4ded751c8bdfb$export$4c260019440d418f;
  const $3dc4ded751c8bdfb$export$353f5b6fc5456de1 = $3dc4ded751c8bdfb$export$e5c1a33878e86e9e;
  const $3dc4ded751c8bdfb$export$a6c7ac8248d6e38a = $3dc4ded751c8bdfb$export$ff5714eba66809fd;
  const fetchAllQuestions = async () => {
    const contentContainer = document.querySelector(".wl-search");
    if (contentContainer) {
      contentContainer.innerHTML = "";
    }
    let currentDocument = document;
    let currentNextLink = currentDocument.querySelector(ELEM_WL_PAGE_EXERCISE_EXPLORE_SECTION_LINK_FIRST_PAGE_SELECTOR);
    let successfullyLoadedPages = 0;
    let errorDuringQuestionLoading = false;
    for (let i2 = 0; currentNextLink && i2 < VAL_PAGE_EXERCISE_EXPLORE_SECTION_MAX_ITERATIONS; i2++) {
      const currentNextHref = currentNextLink.href;
      try {
        const response = await fetch(currentNextHref);
        const html = await response.text();
        const parser = new DOMParser();
        currentDocument = parser.parseFromString(html, "text/html");
        const questionsTable = currentDocument.querySelector(ELEM_WL_PAGE_EXERCISE_EXPLORE_SECTION_QUESTIONS_TABLE_SELECTOR);
        if (questionsTable && contentContainer) {
          const titleElement = document.createElement("h3");
          titleElement.innerText = instance.t(`${LANG_NS_MAIN}:page`, {
            count: i2 + 1
          });
          titleElement.classList.add("HeadingPage");
          contentContainer.append(titleElement);
          contentContainer.append(questionsTable);
          successfullyLoadedPages++;
        } else {
          currentNextLink = null;
          errorDuringQuestionLoading = true;
          break;
        }
        currentNextLink = currentDocument.querySelector(ELEM_WL_PAGE_EXERCISE_EXPLORE_SECTION_LINK_NEXT_PAGE_SELECTOR);
      } catch (err) {
        throw Error(`Failed to load pages. Reason: ${err}`);
      }
    }
    if (errorDuringQuestionLoading) {
      throw Error("Failed to load pages");
    } else if (successfullyLoadedPages >= 0) {
      return {
        success: true,
        loadedPages: successfullyLoadedPages
      };
    }
  };
  const ExploreSectionsToolbar = () => {
    const notificationContext = q$1(NotificationContext);
    const [pagesHaveBeenLoaded, setPagesHaveBeenLoaded] = h(false);
    function onClickShowAllButton() {
      fetchAllQuestions().then((result) => {
        const {
          loadedPages,
          success
        } = result ? result : {
          loadedPages: 0,
          success: false
        };
        if (success && loadedPages > 0) {
          notificationContext.setOptions({
            type: NotificationType.NOTIFICATION,
            title: instance.t(`${LANG_NS_MAIN}:pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsTitle`),
            text: instance.t(`${LANG_NS_MAIN}:pageExerciseExploreSectionNotificationLoadedPagesOfQuestionsText`, {
              count: loadedPages
            })
          });
          setPagesHaveBeenLoaded(true);
        } else {
          notificationContext.setOptions({
            type: NotificationType.WARNING,
            title: instance.t(`${LANG_NS_MAIN}:pageExerciseExploreSectionWarningDuringQuestionLoadTitle`),
            text: instance.t(`${LANG_NS_MAIN}:pageExerciseExploreSectionWarningDuringQuestionLoadText`)
          });
        }
      }).catch(() => {
        notificationContext.setOptions({
          type: NotificationType.ERROR,
          title: instance.t(`${LANG_NS_MAIN}:pageExerciseExploreSectionErrorDuringQuestionLoadTitle`),
          text: instance.t(`${LANG_NS_MAIN}:pageExerciseExploreSectionErrorDuringQuestionLoadText`)
        });
      });
    }
    return o($3dc4ded751c8bdfb$export$be92b6f5f03c0fe9, {
      className: "ToolbarRoot ExploreSectionsToolbarRoot",
      "aria-label": "Formatting options",
      children: o($3dc4ded751c8bdfb$export$353f5b6fc5456de1, {
        className: "ToolbarButton",
        disabled: pagesHaveBeenLoaded,
        onClick: onClickShowAllButton,
        children: [o(FilePlusIcon, {}), o("span", {
          className: "ToolbarButtonText",
          children: !pagesHaveBeenLoaded && instance.t(`${LANG_NS_MAIN}:pageExerciseExploreSectionShowAllQuestionsButton`) || instance.t(`${LANG_NS_MAIN}:pageExerciseExploreSectionShowAllQuestionsButtonDisabled`)
        })]
      })
    });
  };
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const CONSTANTS = {
    /**
     * @define {boolean} Whether this is the client Node.js SDK.
     */
    NODE_CLIENT: false,
    /**
     * @define {boolean} Whether this is the Admin Node.js SDK.
     */
    NODE_ADMIN: false,
    /**
     * Firebase SDK Version
     */
    SDK_VERSION: "${JSCORE_VERSION}"
  };
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const assert = function(assertion, message) {
    if (!assertion) {
      throw assertionError(message);
    }
  };
  const assertionError = function(message) {
    return new Error("Firebase Database (" + CONSTANTS.SDK_VERSION + ") INTERNAL ASSERT FAILED: " + message);
  };
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const stringToByteArray$1 = function(str) {
    const out = [];
    let p2 = 0;
    for (let i2 = 0; i2 < str.length; i2++) {
      let c2 = str.charCodeAt(i2);
      if (c2 < 128) {
        out[p2++] = c2;
      } else if (c2 < 2048) {
        out[p2++] = c2 >> 6 | 192;
        out[p2++] = c2 & 63 | 128;
      } else if ((c2 & 64512) === 55296 && i2 + 1 < str.length && (str.charCodeAt(i2 + 1) & 64512) === 56320) {
        c2 = 65536 + ((c2 & 1023) << 10) + (str.charCodeAt(++i2) & 1023);
        out[p2++] = c2 >> 18 | 240;
        out[p2++] = c2 >> 12 & 63 | 128;
        out[p2++] = c2 >> 6 & 63 | 128;
        out[p2++] = c2 & 63 | 128;
      } else {
        out[p2++] = c2 >> 12 | 224;
        out[p2++] = c2 >> 6 & 63 | 128;
        out[p2++] = c2 & 63 | 128;
      }
    }
    return out;
  };
  const byteArrayToString = function(bytes) {
    const out = [];
    let pos = 0, c2 = 0;
    while (pos < bytes.length) {
      const c1 = bytes[pos++];
      if (c1 < 128) {
        out[c2++] = String.fromCharCode(c1);
      } else if (c1 > 191 && c1 < 224) {
        const c22 = bytes[pos++];
        out[c2++] = String.fromCharCode((c1 & 31) << 6 | c22 & 63);
      } else if (c1 > 239 && c1 < 365) {
        const c22 = bytes[pos++];
        const c3 = bytes[pos++];
        const c4 = bytes[pos++];
        const u2 = ((c1 & 7) << 18 | (c22 & 63) << 12 | (c3 & 63) << 6 | c4 & 63) - 65536;
        out[c2++] = String.fromCharCode(55296 + (u2 >> 10));
        out[c2++] = String.fromCharCode(56320 + (u2 & 1023));
      } else {
        const c22 = bytes[pos++];
        const c3 = bytes[pos++];
        out[c2++] = String.fromCharCode((c1 & 15) << 12 | (c22 & 63) << 6 | c3 & 63);
      }
    }
    return out.join("");
  };
  const base64 = {
    /**
     * Maps bytes to characters.
     */
    byteToCharMap_: null,
    /**
     * Maps characters to bytes.
     */
    charToByteMap_: null,
    /**
     * Maps bytes to websafe characters.
     * @private
     */
    byteToCharMapWebSafe_: null,
    /**
     * Maps websafe characters to bytes.
     * @private
     */
    charToByteMapWebSafe_: null,
    /**
     * Our default alphabet, shared between
     * ENCODED_VALS and ENCODED_VALS_WEBSAFE
     */
    ENCODED_VALS_BASE: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",
    /**
     * Our default alphabet. Value 64 (=) is special; it means "nothing."
     */
    get ENCODED_VALS() {
      return this.ENCODED_VALS_BASE + "+/=";
    },
    /**
     * Our websafe alphabet.
     */
    get ENCODED_VALS_WEBSAFE() {
      return this.ENCODED_VALS_BASE + "-_.";
    },
    /**
     * Whether this browser supports the atob and btoa functions. This extension
     * started at Mozilla but is now implemented by many browsers. We use the
     * ASSUME_* variables to avoid pulling in the full useragent detection library
     * but still allowing the standard per-browser compilations.
     *
     */
    HAS_NATIVE_SUPPORT: typeof atob === "function",
    /**
     * Base64-encode an array of bytes.
     *
     * @param input An array of bytes (numbers with
     *     value in [0, 255]) to encode.
     * @param webSafe Boolean indicating we should use the
     *     alternative alphabet.
     * @return The base64 encoded string.
     */
    encodeByteArray(input, webSafe) {
      if (!Array.isArray(input)) {
        throw Error("encodeByteArray takes an array as a parameter");
      }
      this.init_();
      const byteToCharMap = webSafe ? this.byteToCharMapWebSafe_ : this.byteToCharMap_;
      const output = [];
      for (let i2 = 0; i2 < input.length; i2 += 3) {
        const byte1 = input[i2];
        const haveByte2 = i2 + 1 < input.length;
        const byte2 = haveByte2 ? input[i2 + 1] : 0;
        const haveByte3 = i2 + 2 < input.length;
        const byte3 = haveByte3 ? input[i2 + 2] : 0;
        const outByte1 = byte1 >> 2;
        const outByte2 = (byte1 & 3) << 4 | byte2 >> 4;
        let outByte3 = (byte2 & 15) << 2 | byte3 >> 6;
        let outByte4 = byte3 & 63;
        if (!haveByte3) {
          outByte4 = 64;
          if (!haveByte2) {
            outByte3 = 64;
          }
        }
        output.push(byteToCharMap[outByte1], byteToCharMap[outByte2], byteToCharMap[outByte3], byteToCharMap[outByte4]);
      }
      return output.join("");
    },
    /**
     * Base64-encode a string.
     *
     * @param input A string to encode.
     * @param webSafe If true, we should use the
     *     alternative alphabet.
     * @return The base64 encoded string.
     */
    encodeString(input, webSafe) {
      if (this.HAS_NATIVE_SUPPORT && !webSafe) {
        return btoa(input);
      }
      return this.encodeByteArray(stringToByteArray$1(input), webSafe);
    },
    /**
     * Base64-decode a string.
     *
     * @param input to decode.
     * @param webSafe True if we should use the
     *     alternative alphabet.
     * @return string representing the decoded value.
     */
    decodeString(input, webSafe) {
      if (this.HAS_NATIVE_SUPPORT && !webSafe) {
        return atob(input);
      }
      return byteArrayToString(this.decodeStringToByteArray(input, webSafe));
    },
    /**
     * Base64-decode a string.
     *
     * In base-64 decoding, groups of four characters are converted into three
     * bytes.  If the encoder did not apply padding, the input length may not
     * be a multiple of 4.
     *
     * In this case, the last group will have fewer than 4 characters, and
     * padding will be inferred.  If the group has one or two characters, it decodes
     * to one byte.  If the group has three characters, it decodes to two bytes.
     *
     * @param input Input to decode.
     * @param webSafe True if we should use the web-safe alphabet.
     * @return bytes representing the decoded value.
     */
    decodeStringToByteArray(input, webSafe) {
      this.init_();
      const charToByteMap = webSafe ? this.charToByteMapWebSafe_ : this.charToByteMap_;
      const output = [];
      for (let i2 = 0; i2 < input.length; ) {
        const byte1 = charToByteMap[input.charAt(i2++)];
        const haveByte2 = i2 < input.length;
        const byte2 = haveByte2 ? charToByteMap[input.charAt(i2)] : 0;
        ++i2;
        const haveByte3 = i2 < input.length;
        const byte3 = haveByte3 ? charToByteMap[input.charAt(i2)] : 64;
        ++i2;
        const haveByte4 = i2 < input.length;
        const byte4 = haveByte4 ? charToByteMap[input.charAt(i2)] : 64;
        ++i2;
        if (byte1 == null || byte2 == null || byte3 == null || byte4 == null) {
          throw new DecodeBase64StringError();
        }
        const outByte1 = byte1 << 2 | byte2 >> 4;
        output.push(outByte1);
        if (byte3 !== 64) {
          const outByte2 = byte2 << 4 & 240 | byte3 >> 2;
          output.push(outByte2);
          if (byte4 !== 64) {
            const outByte3 = byte3 << 6 & 192 | byte4;
            output.push(outByte3);
          }
        }
      }
      return output;
    },
    /**
     * Lazy static initialization function. Called before
     * accessing any of the static map variables.
     * @private
     */
    init_() {
      if (!this.byteToCharMap_) {
        this.byteToCharMap_ = {};
        this.charToByteMap_ = {};
        this.byteToCharMapWebSafe_ = {};
        this.charToByteMapWebSafe_ = {};
        for (let i2 = 0; i2 < this.ENCODED_VALS.length; i2++) {
          this.byteToCharMap_[i2] = this.ENCODED_VALS.charAt(i2);
          this.charToByteMap_[this.byteToCharMap_[i2]] = i2;
          this.byteToCharMapWebSafe_[i2] = this.ENCODED_VALS_WEBSAFE.charAt(i2);
          this.charToByteMapWebSafe_[this.byteToCharMapWebSafe_[i2]] = i2;
          if (i2 >= this.ENCODED_VALS_BASE.length) {
            this.charToByteMap_[this.ENCODED_VALS_WEBSAFE.charAt(i2)] = i2;
            this.charToByteMapWebSafe_[this.ENCODED_VALS.charAt(i2)] = i2;
          }
        }
      }
    }
  };
  class DecodeBase64StringError extends Error {
    constructor() {
      super(...arguments);
      this.name = "DecodeBase64StringError";
    }
  }
  const base64Encode = function(str) {
    const utf8Bytes = stringToByteArray$1(str);
    return base64.encodeByteArray(utf8Bytes, true);
  };
  const base64urlEncodeWithoutPadding = function(str) {
    return base64Encode(str).replace(/\./g, "");
  };
  const base64Decode = function(str) {
    try {
      return base64.decodeString(str, true);
    } catch (e2) {
      console.error("base64Decode failed: ", e2);
    }
    return null;
  };
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function deepCopy(value) {
    return deepExtend(void 0, value);
  }
  function deepExtend(target, source) {
    if (!(source instanceof Object)) {
      return source;
    }
    switch (source.constructor) {
      case Date:
        const dateValue = source;
        return new Date(dateValue.getTime());
      case Object:
        if (target === void 0) {
          target = {};
        }
        break;
      case Array:
        target = [];
        break;
      default:
        return source;
    }
    for (const prop in source) {
      if (!source.hasOwnProperty(prop) || !isValidKey$1(prop)) {
        continue;
      }
      target[prop] = deepExtend(target[prop], source[prop]);
    }
    return target;
  }
  function isValidKey$1(key) {
    return key !== "__proto__";
  }
  /**
   * @license
   * Copyright 2022 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function getGlobal() {
    if (typeof self !== "undefined") {
      return self;
    }
    if (typeof window !== "undefined") {
      return window;
    }
    if (typeof global !== "undefined") {
      return global;
    }
    throw new Error("Unable to locate global object.");
  }
  /**
   * @license
   * Copyright 2022 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__;
  const getDefaultsFromEnvVariable = () => {
    if (typeof process === "undefined" || typeof process.env === "undefined") {
      return;
    }
    const defaultsJsonString = {}.__FIREBASE_DEFAULTS__;
    if (defaultsJsonString) {
      return JSON.parse(defaultsJsonString);
    }
  };
  const getDefaultsFromCookie = () => {
    if (typeof document === "undefined") {
      return;
    }
    let match;
    try {
      match = document.cookie.match(/__FIREBASE_DEFAULTS__=([^;]+)/);
    } catch (e2) {
      return;
    }
    const decoded = match && base64Decode(match[1]);
    return decoded && JSON.parse(decoded);
  };
  const getDefaults = () => {
    try {
      return getDefaultsFromGlobal() || getDefaultsFromEnvVariable() || getDefaultsFromCookie();
    } catch (e2) {
      console.info(`Unable to get __FIREBASE_DEFAULTS__ due to: ${e2}`);
      return;
    }
  };
  const getDefaultEmulatorHost = (productName) => {
    var _a2, _b;
    return (_b = (_a2 = getDefaults()) === null || _a2 === void 0 ? void 0 : _a2.emulatorHosts) === null || _b === void 0 ? void 0 : _b[productName];
  };
  const getDefaultEmulatorHostnameAndPort = (productName) => {
    const host = getDefaultEmulatorHost(productName);
    if (!host) {
      return void 0;
    }
    const separatorIndex = host.lastIndexOf(":");
    if (separatorIndex <= 0 || separatorIndex + 1 === host.length) {
      throw new Error(`Invalid host ${host} with no separate hostname and port!`);
    }
    const port = parseInt(host.substring(separatorIndex + 1), 10);
    if (host[0] === "[") {
      return [host.substring(1, separatorIndex - 1), port];
    } else {
      return [host.substring(0, separatorIndex), port];
    }
  };
  const getDefaultAppConfig = () => {
    var _a2;
    return (_a2 = getDefaults()) === null || _a2 === void 0 ? void 0 : _a2.config;
  };
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class Deferred {
    constructor() {
      this.reject = () => {
      };
      this.resolve = () => {
      };
      this.promise = new Promise((resolve, reject) => {
        this.resolve = resolve;
        this.reject = reject;
      });
    }
    /**
     * Our API internals are not promiseified and cannot because our callback APIs have subtle expectations around
     * invoking promises inline, which Promises are forbidden to do. This method accepts an optional node-style callback
     * and returns a node-style callback which will resolve or reject the Deferred's promise.
     */
    wrapCallback(callback) {
      return (error2, value) => {
        if (error2) {
          this.reject(error2);
        } else {
          this.resolve(value);
        }
        if (typeof callback === "function") {
          this.promise.catch(() => {
          });
          if (callback.length === 1) {
            callback(error2);
          } else {
            callback(error2, value);
          }
        }
      };
    }
  }
  /**
   * @license
   * Copyright 2021 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function createMockUserToken(token, projectId) {
    if (token.uid) {
      throw new Error('The "uid" field is no longer supported by mockUserToken. Please use "sub" instead for Firebase Auth User ID.');
    }
    const header = {
      alg: "none",
      type: "JWT"
    };
    const project = projectId || "demo-project";
    const iat = token.iat || 0;
    const sub = token.sub || token.user_id;
    if (!sub) {
      throw new Error("mockUserToken must contain 'sub' or 'user_id' field!");
    }
    const payload = Object.assign({
      // Set all required fields to decent defaults
      iss: `https://securetoken.google.com/${project}`,
      aud: project,
      iat,
      exp: iat + 3600,
      auth_time: iat,
      sub,
      user_id: sub,
      firebase: {
        sign_in_provider: "custom",
        identities: {}
      }
    }, token);
    const signature = "";
    return [
      base64urlEncodeWithoutPadding(JSON.stringify(header)),
      base64urlEncodeWithoutPadding(JSON.stringify(payload)),
      signature
    ].join(".");
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function getUA() {
    if (typeof navigator !== "undefined" && typeof navigator["userAgent"] === "string") {
      return navigator["userAgent"];
    } else {
      return "";
    }
  }
  function isMobileCordova() {
    return typeof window !== "undefined" && // @ts-ignore Setting up an broadly applicable index signature for Window
    // just to deal with this case would probably be a bad idea.
    !!(window["cordova"] || window["phonegap"] || window["PhoneGap"]) && /ios|iphone|ipod|ipad|android|blackberry|iemobile/i.test(getUA());
  }
  function isReactNative() {
    return typeof navigator === "object" && navigator["product"] === "ReactNative";
  }
  function isNodeSdk() {
    return CONSTANTS.NODE_ADMIN === true;
  }
  function isIndexedDBAvailable() {
    try {
      return typeof indexedDB === "object";
    } catch (e2) {
      return false;
    }
  }
  function validateIndexedDBOpenable() {
    return new Promise((resolve, reject) => {
      try {
        let preExist = true;
        const DB_CHECK_NAME = "validate-browser-context-for-indexeddb-analytics-module";
        const request = self.indexedDB.open(DB_CHECK_NAME);
        request.onsuccess = () => {
          request.result.close();
          if (!preExist) {
            self.indexedDB.deleteDatabase(DB_CHECK_NAME);
          }
          resolve(true);
        };
        request.onupgradeneeded = () => {
          preExist = false;
        };
        request.onerror = () => {
          var _a2;
          reject(((_a2 = request.error) === null || _a2 === void 0 ? void 0 : _a2.message) || "");
        };
      } catch (error2) {
        reject(error2);
      }
    });
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const ERROR_NAME = "FirebaseError";
  class FirebaseError extends Error {
    constructor(code, message, customData) {
      super(message);
      this.code = code;
      this.customData = customData;
      this.name = ERROR_NAME;
      Object.setPrototypeOf(this, FirebaseError.prototype);
      if (Error.captureStackTrace) {
        Error.captureStackTrace(this, ErrorFactory.prototype.create);
      }
    }
  }
  class ErrorFactory {
    constructor(service, serviceName, errors) {
      this.service = service;
      this.serviceName = serviceName;
      this.errors = errors;
    }
    create(code, ...data) {
      const customData = data[0] || {};
      const fullCode = `${this.service}/${code}`;
      const template = this.errors[code];
      const message = template ? replaceTemplate(template, customData) : "Error";
      const fullMessage = `${this.serviceName}: ${message} (${fullCode}).`;
      const error2 = new FirebaseError(fullCode, fullMessage, customData);
      return error2;
    }
  }
  function replaceTemplate(template, data) {
    return template.replace(PATTERN, (_2, key) => {
      const value = data[key];
      return value != null ? String(value) : `<${key}?>`;
    });
  }
  const PATTERN = /\{\$([^}]+)}/g;
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function jsonEval(str) {
    return JSON.parse(str);
  }
  function stringify(data) {
    return JSON.stringify(data);
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const decode = function(token) {
    let header = {}, claims = {}, data = {}, signature = "";
    try {
      const parts = token.split(".");
      header = jsonEval(base64Decode(parts[0]) || "");
      claims = jsonEval(base64Decode(parts[1]) || "");
      signature = parts[2];
      data = claims["d"] || {};
      delete claims["d"];
    } catch (e2) {
    }
    return {
      header,
      claims,
      data,
      signature
    };
  };
  const isValidFormat = function(token) {
    const decoded = decode(token), claims = decoded.claims;
    return !!claims && typeof claims === "object" && claims.hasOwnProperty("iat");
  };
  const isAdmin = function(token) {
    const claims = decode(token).claims;
    return typeof claims === "object" && claims["admin"] === true;
  };
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function contains(obj, key) {
    return Object.prototype.hasOwnProperty.call(obj, key);
  }
  function safeGet(obj, key) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      return obj[key];
    } else {
      return void 0;
    }
  }
  function isEmpty(obj) {
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        return false;
      }
    }
    return true;
  }
  function map(obj, fn2, contextObj) {
    const res = {};
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        res[key] = fn2.call(contextObj, obj[key], key, obj);
      }
    }
    return res;
  }
  function deepEqual(a2, b2) {
    if (a2 === b2) {
      return true;
    }
    const aKeys = Object.keys(a2);
    const bKeys = Object.keys(b2);
    for (const k2 of aKeys) {
      if (!bKeys.includes(k2)) {
        return false;
      }
      const aProp = a2[k2];
      const bProp = b2[k2];
      if (isObject(aProp) && isObject(bProp)) {
        if (!deepEqual(aProp, bProp)) {
          return false;
        }
      } else if (aProp !== bProp) {
        return false;
      }
    }
    for (const k2 of bKeys) {
      if (!aKeys.includes(k2)) {
        return false;
      }
    }
    return true;
  }
  function isObject(thing) {
    return thing !== null && typeof thing === "object";
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function querystring(querystringParams) {
    const params = [];
    for (const [key, value] of Object.entries(querystringParams)) {
      if (Array.isArray(value)) {
        value.forEach((arrayVal) => {
          params.push(encodeURIComponent(key) + "=" + encodeURIComponent(arrayVal));
        });
      } else {
        params.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
      }
    }
    return params.length ? "&" + params.join("&") : "";
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class Sha1 {
    constructor() {
      this.chain_ = [];
      this.buf_ = [];
      this.W_ = [];
      this.pad_ = [];
      this.inbuf_ = 0;
      this.total_ = 0;
      this.blockSize = 512 / 8;
      this.pad_[0] = 128;
      for (let i2 = 1; i2 < this.blockSize; ++i2) {
        this.pad_[i2] = 0;
      }
      this.reset();
    }
    reset() {
      this.chain_[0] = 1732584193;
      this.chain_[1] = 4023233417;
      this.chain_[2] = 2562383102;
      this.chain_[3] = 271733878;
      this.chain_[4] = 3285377520;
      this.inbuf_ = 0;
      this.total_ = 0;
    }
    /**
     * Internal compress helper function.
     * @param buf Block to compress.
     * @param offset Offset of the block in the buffer.
     * @private
     */
    compress_(buf, offset) {
      if (!offset) {
        offset = 0;
      }
      const W2 = this.W_;
      if (typeof buf === "string") {
        for (let i2 = 0; i2 < 16; i2++) {
          W2[i2] = buf.charCodeAt(offset) << 24 | buf.charCodeAt(offset + 1) << 16 | buf.charCodeAt(offset + 2) << 8 | buf.charCodeAt(offset + 3);
          offset += 4;
        }
      } else {
        for (let i2 = 0; i2 < 16; i2++) {
          W2[i2] = buf[offset] << 24 | buf[offset + 1] << 16 | buf[offset + 2] << 8 | buf[offset + 3];
          offset += 4;
        }
      }
      for (let i2 = 16; i2 < 80; i2++) {
        const t2 = W2[i2 - 3] ^ W2[i2 - 8] ^ W2[i2 - 14] ^ W2[i2 - 16];
        W2[i2] = (t2 << 1 | t2 >>> 31) & 4294967295;
      }
      let a2 = this.chain_[0];
      let b2 = this.chain_[1];
      let c2 = this.chain_[2];
      let d2 = this.chain_[3];
      let e2 = this.chain_[4];
      let f2, k2;
      for (let i2 = 0; i2 < 80; i2++) {
        if (i2 < 40) {
          if (i2 < 20) {
            f2 = d2 ^ b2 & (c2 ^ d2);
            k2 = 1518500249;
          } else {
            f2 = b2 ^ c2 ^ d2;
            k2 = 1859775393;
          }
        } else {
          if (i2 < 60) {
            f2 = b2 & c2 | d2 & (b2 | c2);
            k2 = 2400959708;
          } else {
            f2 = b2 ^ c2 ^ d2;
            k2 = 3395469782;
          }
        }
        const t2 = (a2 << 5 | a2 >>> 27) + f2 + e2 + k2 + W2[i2] & 4294967295;
        e2 = d2;
        d2 = c2;
        c2 = (b2 << 30 | b2 >>> 2) & 4294967295;
        b2 = a2;
        a2 = t2;
      }
      this.chain_[0] = this.chain_[0] + a2 & 4294967295;
      this.chain_[1] = this.chain_[1] + b2 & 4294967295;
      this.chain_[2] = this.chain_[2] + c2 & 4294967295;
      this.chain_[3] = this.chain_[3] + d2 & 4294967295;
      this.chain_[4] = this.chain_[4] + e2 & 4294967295;
    }
    update(bytes, length) {
      if (bytes == null) {
        return;
      }
      if (length === void 0) {
        length = bytes.length;
      }
      const lengthMinusBlock = length - this.blockSize;
      let n2 = 0;
      const buf = this.buf_;
      let inbuf = this.inbuf_;
      while (n2 < length) {
        if (inbuf === 0) {
          while (n2 <= lengthMinusBlock) {
            this.compress_(bytes, n2);
            n2 += this.blockSize;
          }
        }
        if (typeof bytes === "string") {
          while (n2 < length) {
            buf[inbuf] = bytes.charCodeAt(n2);
            ++inbuf;
            ++n2;
            if (inbuf === this.blockSize) {
              this.compress_(buf);
              inbuf = 0;
              break;
            }
          }
        } else {
          while (n2 < length) {
            buf[inbuf] = bytes[n2];
            ++inbuf;
            ++n2;
            if (inbuf === this.blockSize) {
              this.compress_(buf);
              inbuf = 0;
              break;
            }
          }
        }
      }
      this.inbuf_ = inbuf;
      this.total_ += length;
    }
    /** @override */
    digest() {
      const digest = [];
      let totalBits = this.total_ * 8;
      if (this.inbuf_ < 56) {
        this.update(this.pad_, 56 - this.inbuf_);
      } else {
        this.update(this.pad_, this.blockSize - (this.inbuf_ - 56));
      }
      for (let i2 = this.blockSize - 1; i2 >= 56; i2--) {
        this.buf_[i2] = totalBits & 255;
        totalBits /= 256;
      }
      this.compress_(this.buf_);
      let n2 = 0;
      for (let i2 = 0; i2 < 5; i2++) {
        for (let j2 = 24; j2 >= 0; j2 -= 8) {
          digest[n2] = this.chain_[i2] >> j2 & 255;
          ++n2;
        }
      }
      return digest;
    }
  }
  function errorPrefix(fnName, argName) {
    return `${fnName} failed: ${argName} argument `;
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const stringToByteArray = function(str) {
    const out = [];
    let p2 = 0;
    for (let i2 = 0; i2 < str.length; i2++) {
      let c2 = str.charCodeAt(i2);
      if (c2 >= 55296 && c2 <= 56319) {
        const high = c2 - 55296;
        i2++;
        assert(i2 < str.length, "Surrogate pair missing trail surrogate.");
        const low = str.charCodeAt(i2) - 56320;
        c2 = 65536 + (high << 10) + low;
      }
      if (c2 < 128) {
        out[p2++] = c2;
      } else if (c2 < 2048) {
        out[p2++] = c2 >> 6 | 192;
        out[p2++] = c2 & 63 | 128;
      } else if (c2 < 65536) {
        out[p2++] = c2 >> 12 | 224;
        out[p2++] = c2 >> 6 & 63 | 128;
        out[p2++] = c2 & 63 | 128;
      } else {
        out[p2++] = c2 >> 18 | 240;
        out[p2++] = c2 >> 12 & 63 | 128;
        out[p2++] = c2 >> 6 & 63 | 128;
        out[p2++] = c2 & 63 | 128;
      }
    }
    return out;
  };
  const stringLength = function(str) {
    let p2 = 0;
    for (let i2 = 0; i2 < str.length; i2++) {
      const c2 = str.charCodeAt(i2);
      if (c2 < 128) {
        p2++;
      } else if (c2 < 2048) {
        p2 += 2;
      } else if (c2 >= 55296 && c2 <= 56319) {
        p2 += 4;
        i2++;
      } else {
        p2 += 3;
      }
    }
    return p2;
  };
  /**
   * @license
   * Copyright 2021 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function getModularInstance(service) {
    if (service && service._delegate) {
      return service._delegate;
    } else {
      return service;
    }
  }
  class Component {
    /**
     *
     * @param name The public service name, e.g. app, auth, firestore, database
     * @param instanceFactory Service factory responsible for creating the public interface
     * @param type whether the service provided by the component is public or private
     */
    constructor(name2, instanceFactory, type) {
      this.name = name2;
      this.instanceFactory = instanceFactory;
      this.type = type;
      this.multipleInstances = false;
      this.serviceProps = {};
      this.instantiationMode = "LAZY";
      this.onInstanceCreated = null;
    }
    setInstantiationMode(mode) {
      this.instantiationMode = mode;
      return this;
    }
    setMultipleInstances(multipleInstances) {
      this.multipleInstances = multipleInstances;
      return this;
    }
    setServiceProps(props) {
      this.serviceProps = props;
      return this;
    }
    setInstanceCreatedCallback(callback) {
      this.onInstanceCreated = callback;
      return this;
    }
  }
  /**
   * @license
   * Copyright 2019 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const DEFAULT_ENTRY_NAME$1 = "[DEFAULT]";
  /**
   * @license
   * Copyright 2019 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class Provider {
    constructor(name2, container) {
      this.name = name2;
      this.container = container;
      this.component = null;
      this.instances = /* @__PURE__ */ new Map();
      this.instancesDeferred = /* @__PURE__ */ new Map();
      this.instancesOptions = /* @__PURE__ */ new Map();
      this.onInitCallbacks = /* @__PURE__ */ new Map();
    }
    /**
     * @param identifier A provider can provide mulitple instances of a service
     * if this.component.multipleInstances is true.
     */
    get(identifier) {
      const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
      if (!this.instancesDeferred.has(normalizedIdentifier)) {
        const deferred = new Deferred();
        this.instancesDeferred.set(normalizedIdentifier, deferred);
        if (this.isInitialized(normalizedIdentifier) || this.shouldAutoInitialize()) {
          try {
            const instance2 = this.getOrInitializeService({
              instanceIdentifier: normalizedIdentifier
            });
            if (instance2) {
              deferred.resolve(instance2);
            }
          } catch (e2) {
          }
        }
      }
      return this.instancesDeferred.get(normalizedIdentifier).promise;
    }
    getImmediate(options) {
      var _a2;
      const normalizedIdentifier = this.normalizeInstanceIdentifier(options === null || options === void 0 ? void 0 : options.identifier);
      const optional = (_a2 = options === null || options === void 0 ? void 0 : options.optional) !== null && _a2 !== void 0 ? _a2 : false;
      if (this.isInitialized(normalizedIdentifier) || this.shouldAutoInitialize()) {
        try {
          return this.getOrInitializeService({
            instanceIdentifier: normalizedIdentifier
          });
        } catch (e2) {
          if (optional) {
            return null;
          } else {
            throw e2;
          }
        }
      } else {
        if (optional) {
          return null;
        } else {
          throw Error(`Service ${this.name} is not available`);
        }
      }
    }
    getComponent() {
      return this.component;
    }
    setComponent(component) {
      if (component.name !== this.name) {
        throw Error(`Mismatching Component ${component.name} for Provider ${this.name}.`);
      }
      if (this.component) {
        throw Error(`Component for ${this.name} has already been provided`);
      }
      this.component = component;
      if (!this.shouldAutoInitialize()) {
        return;
      }
      if (isComponentEager(component)) {
        try {
          this.getOrInitializeService({ instanceIdentifier: DEFAULT_ENTRY_NAME$1 });
        } catch (e2) {
        }
      }
      for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {
        const normalizedIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
        try {
          const instance2 = this.getOrInitializeService({
            instanceIdentifier: normalizedIdentifier
          });
          instanceDeferred.resolve(instance2);
        } catch (e2) {
        }
      }
    }
    clearInstance(identifier = DEFAULT_ENTRY_NAME$1) {
      this.instancesDeferred.delete(identifier);
      this.instancesOptions.delete(identifier);
      this.instances.delete(identifier);
    }
    // app.delete() will call this method on every provider to delete the services
    // TODO: should we mark the provider as deleted?
    async delete() {
      const services = Array.from(this.instances.values());
      await Promise.all([
        ...services.filter((service) => "INTERNAL" in service).map((service) => service.INTERNAL.delete()),
        ...services.filter((service) => "_delete" in service).map((service) => service._delete())
      ]);
    }
    isComponentSet() {
      return this.component != null;
    }
    isInitialized(identifier = DEFAULT_ENTRY_NAME$1) {
      return this.instances.has(identifier);
    }
    getOptions(identifier = DEFAULT_ENTRY_NAME$1) {
      return this.instancesOptions.get(identifier) || {};
    }
    initialize(opts = {}) {
      const { options = {} } = opts;
      const normalizedIdentifier = this.normalizeInstanceIdentifier(opts.instanceIdentifier);
      if (this.isInitialized(normalizedIdentifier)) {
        throw Error(`${this.name}(${normalizedIdentifier}) has already been initialized`);
      }
      if (!this.isComponentSet()) {
        throw Error(`Component ${this.name} has not been registered yet`);
      }
      const instance2 = this.getOrInitializeService({
        instanceIdentifier: normalizedIdentifier,
        options
      });
      for (const [instanceIdentifier, instanceDeferred] of this.instancesDeferred.entries()) {
        const normalizedDeferredIdentifier = this.normalizeInstanceIdentifier(instanceIdentifier);
        if (normalizedIdentifier === normalizedDeferredIdentifier) {
          instanceDeferred.resolve(instance2);
        }
      }
      return instance2;
    }
    /**
     *
     * @param callback - a function that will be invoked  after the provider has been initialized by calling provider.initialize().
     * The function is invoked SYNCHRONOUSLY, so it should not execute any longrunning tasks in order to not block the program.
     *
     * @param identifier An optional instance identifier
     * @returns a function to unregister the callback
     */
    onInit(callback, identifier) {
      var _a2;
      const normalizedIdentifier = this.normalizeInstanceIdentifier(identifier);
      const existingCallbacks = (_a2 = this.onInitCallbacks.get(normalizedIdentifier)) !== null && _a2 !== void 0 ? _a2 : /* @__PURE__ */ new Set();
      existingCallbacks.add(callback);
      this.onInitCallbacks.set(normalizedIdentifier, existingCallbacks);
      const existingInstance = this.instances.get(normalizedIdentifier);
      if (existingInstance) {
        callback(existingInstance, normalizedIdentifier);
      }
      return () => {
        existingCallbacks.delete(callback);
      };
    }
    /**
     * Invoke onInit callbacks synchronously
     * @param instance the service instance`
     */
    invokeOnInitCallbacks(instance2, identifier) {
      const callbacks = this.onInitCallbacks.get(identifier);
      if (!callbacks) {
        return;
      }
      for (const callback of callbacks) {
        try {
          callback(instance2, identifier);
        } catch (_a2) {
        }
      }
    }
    getOrInitializeService({ instanceIdentifier, options = {} }) {
      let instance2 = this.instances.get(instanceIdentifier);
      if (!instance2 && this.component) {
        instance2 = this.component.instanceFactory(this.container, {
          instanceIdentifier: normalizeIdentifierForFactory(instanceIdentifier),
          options
        });
        this.instances.set(instanceIdentifier, instance2);
        this.instancesOptions.set(instanceIdentifier, options);
        this.invokeOnInitCallbacks(instance2, instanceIdentifier);
        if (this.component.onInstanceCreated) {
          try {
            this.component.onInstanceCreated(this.container, instanceIdentifier, instance2);
          } catch (_a2) {
          }
        }
      }
      return instance2 || null;
    }
    normalizeInstanceIdentifier(identifier = DEFAULT_ENTRY_NAME$1) {
      if (this.component) {
        return this.component.multipleInstances ? identifier : DEFAULT_ENTRY_NAME$1;
      } else {
        return identifier;
      }
    }
    shouldAutoInitialize() {
      return !!this.component && this.component.instantiationMode !== "EXPLICIT";
    }
  }
  function normalizeIdentifierForFactory(identifier) {
    return identifier === DEFAULT_ENTRY_NAME$1 ? void 0 : identifier;
  }
  function isComponentEager(component) {
    return component.instantiationMode === "EAGER";
  }
  /**
   * @license
   * Copyright 2019 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class ComponentContainer {
    constructor(name2) {
      this.name = name2;
      this.providers = /* @__PURE__ */ new Map();
    }
    /**
     *
     * @param component Component being added
     * @param overwrite When a component with the same name has already been registered,
     * if overwrite is true: overwrite the existing component with the new component and create a new
     * provider with the new component. It can be useful in tests where you want to use different mocks
     * for different tests.
     * if overwrite is false: throw an exception
     */
    addComponent(component) {
      const provider = this.getProvider(component.name);
      if (provider.isComponentSet()) {
        throw new Error(`Component ${component.name} has already been registered with ${this.name}`);
      }
      provider.setComponent(component);
    }
    addOrOverwriteComponent(component) {
      const provider = this.getProvider(component.name);
      if (provider.isComponentSet()) {
        this.providers.delete(component.name);
      }
      this.addComponent(component);
    }
    /**
     * getProvider provides a type safe interface where it can only be called with a field name
     * present in NameServiceMapping interface.
     *
     * Firebase SDKs providing services should extend NameServiceMapping interface to register
     * themselves.
     */
    getProvider(name2) {
      if (this.providers.has(name2)) {
        return this.providers.get(name2);
      }
      const provider = new Provider(name2, this);
      this.providers.set(name2, provider);
      return provider;
    }
    getProviders() {
      return Array.from(this.providers.values());
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  var LogLevel;
  (function(LogLevel2) {
    LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
    LogLevel2[LogLevel2["VERBOSE"] = 1] = "VERBOSE";
    LogLevel2[LogLevel2["INFO"] = 2] = "INFO";
    LogLevel2[LogLevel2["WARN"] = 3] = "WARN";
    LogLevel2[LogLevel2["ERROR"] = 4] = "ERROR";
    LogLevel2[LogLevel2["SILENT"] = 5] = "SILENT";
  })(LogLevel || (LogLevel = {}));
  const levelStringToEnum = {
    "debug": LogLevel.DEBUG,
    "verbose": LogLevel.VERBOSE,
    "info": LogLevel.INFO,
    "warn": LogLevel.WARN,
    "error": LogLevel.ERROR,
    "silent": LogLevel.SILENT
  };
  const defaultLogLevel = LogLevel.INFO;
  const ConsoleMethod = {
    [LogLevel.DEBUG]: "log",
    [LogLevel.VERBOSE]: "log",
    [LogLevel.INFO]: "info",
    [LogLevel.WARN]: "warn",
    [LogLevel.ERROR]: "error"
  };
  const defaultLogHandler = (instance2, logType, ...args) => {
    if (logType < instance2.logLevel) {
      return;
    }
    const now = (/* @__PURE__ */ new Date()).toISOString();
    const method = ConsoleMethod[logType];
    if (method) {
      console[method](`[${now}]  ${instance2.name}:`, ...args);
    } else {
      throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`);
    }
  };
  class Logger2 {
    /**
     * Gives you an instance of a Logger to capture messages according to
     * Firebase's logging scheme.
     *
     * @param name The name that the logs will be associated with
     */
    constructor(name2) {
      this.name = name2;
      this._logLevel = defaultLogLevel;
      this._logHandler = defaultLogHandler;
      this._userLogHandler = null;
    }
    get logLevel() {
      return this._logLevel;
    }
    set logLevel(val) {
      if (!(val in LogLevel)) {
        throw new TypeError(`Invalid value "${val}" assigned to \`logLevel\``);
      }
      this._logLevel = val;
    }
    // Workaround for setter/getter having to be the same type.
    setLogLevel(val) {
      this._logLevel = typeof val === "string" ? levelStringToEnum[val] : val;
    }
    get logHandler() {
      return this._logHandler;
    }
    set logHandler(val) {
      if (typeof val !== "function") {
        throw new TypeError("Value assigned to `logHandler` must be a function");
      }
      this._logHandler = val;
    }
    get userLogHandler() {
      return this._userLogHandler;
    }
    set userLogHandler(val) {
      this._userLogHandler = val;
    }
    /**
     * The functions below are all based on the `console` interface
     */
    debug(...args) {
      this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args);
      this._logHandler(this, LogLevel.DEBUG, ...args);
    }
    log(...args) {
      this._userLogHandler && this._userLogHandler(this, LogLevel.VERBOSE, ...args);
      this._logHandler(this, LogLevel.VERBOSE, ...args);
    }
    info(...args) {
      this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args);
      this._logHandler(this, LogLevel.INFO, ...args);
    }
    warn(...args) {
      this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args);
      this._logHandler(this, LogLevel.WARN, ...args);
    }
    error(...args) {
      this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args);
      this._logHandler(this, LogLevel.ERROR, ...args);
    }
  }
  const instanceOfAny = (object, constructors) => constructors.some((c2) => object instanceof c2);
  let idbProxyableTypes;
  let cursorAdvanceMethods;
  function getIdbProxyableTypes() {
    return idbProxyableTypes || (idbProxyableTypes = [
      IDBDatabase,
      IDBObjectStore,
      IDBIndex,
      IDBCursor,
      IDBTransaction
    ]);
  }
  function getCursorAdvanceMethods() {
    return cursorAdvanceMethods || (cursorAdvanceMethods = [
      IDBCursor.prototype.advance,
      IDBCursor.prototype.continue,
      IDBCursor.prototype.continuePrimaryKey
    ]);
  }
  const cursorRequestMap = /* @__PURE__ */ new WeakMap();
  const transactionDoneMap = /* @__PURE__ */ new WeakMap();
  const transactionStoreNamesMap = /* @__PURE__ */ new WeakMap();
  const transformCache = /* @__PURE__ */ new WeakMap();
  const reverseTransformCache = /* @__PURE__ */ new WeakMap();
  function promisifyRequest(request) {
    const promise = new Promise((resolve, reject) => {
      const unlisten = () => {
        request.removeEventListener("success", success);
        request.removeEventListener("error", error2);
      };
      const success = () => {
        resolve(wrap(request.result));
        unlisten();
      };
      const error2 = () => {
        reject(request.error);
        unlisten();
      };
      request.addEventListener("success", success);
      request.addEventListener("error", error2);
    });
    promise.then((value) => {
      if (value instanceof IDBCursor) {
        cursorRequestMap.set(value, request);
      }
    }).catch(() => {
    });
    reverseTransformCache.set(promise, request);
    return promise;
  }
  function cacheDonePromiseForTransaction(tx) {
    if (transactionDoneMap.has(tx))
      return;
    const done = new Promise((resolve, reject) => {
      const unlisten = () => {
        tx.removeEventListener("complete", complete);
        tx.removeEventListener("error", error2);
        tx.removeEventListener("abort", error2);
      };
      const complete = () => {
        resolve();
        unlisten();
      };
      const error2 = () => {
        reject(tx.error || new DOMException("AbortError", "AbortError"));
        unlisten();
      };
      tx.addEventListener("complete", complete);
      tx.addEventListener("error", error2);
      tx.addEventListener("abort", error2);
    });
    transactionDoneMap.set(tx, done);
  }
  let idbProxyTraps = {
    get(target, prop, receiver) {
      if (target instanceof IDBTransaction) {
        if (prop === "done")
          return transactionDoneMap.get(target);
        if (prop === "objectStoreNames") {
          return target.objectStoreNames || transactionStoreNamesMap.get(target);
        }
        if (prop === "store") {
          return receiver.objectStoreNames[1] ? void 0 : receiver.objectStore(receiver.objectStoreNames[0]);
        }
      }
      return wrap(target[prop]);
    },
    set(target, prop, value) {
      target[prop] = value;
      return true;
    },
    has(target, prop) {
      if (target instanceof IDBTransaction && (prop === "done" || prop === "store")) {
        return true;
      }
      return prop in target;
    }
  };
  function replaceTraps(callback) {
    idbProxyTraps = callback(idbProxyTraps);
  }
  function wrapFunction(func) {
    if (func === IDBDatabase.prototype.transaction && !("objectStoreNames" in IDBTransaction.prototype)) {
      return function(storeNames, ...args) {
        const tx = func.call(unwrap(this), storeNames, ...args);
        transactionStoreNamesMap.set(tx, storeNames.sort ? storeNames.sort() : [storeNames]);
        return wrap(tx);
      };
    }
    if (getCursorAdvanceMethods().includes(func)) {
      return function(...args) {
        func.apply(unwrap(this), args);
        return wrap(cursorRequestMap.get(this));
      };
    }
    return function(...args) {
      return wrap(func.apply(unwrap(this), args));
    };
  }
  function transformCachableValue(value) {
    if (typeof value === "function")
      return wrapFunction(value);
    if (value instanceof IDBTransaction)
      cacheDonePromiseForTransaction(value);
    if (instanceOfAny(value, getIdbProxyableTypes()))
      return new Proxy(value, idbProxyTraps);
    return value;
  }
  function wrap(value) {
    if (value instanceof IDBRequest)
      return promisifyRequest(value);
    if (transformCache.has(value))
      return transformCache.get(value);
    const newValue = transformCachableValue(value);
    if (newValue !== value) {
      transformCache.set(value, newValue);
      reverseTransformCache.set(newValue, value);
    }
    return newValue;
  }
  const unwrap = (value) => reverseTransformCache.get(value);
  function openDB(name2, version2, { blocked, upgrade, blocking, terminated } = {}) {
    const request = indexedDB.open(name2, version2);
    const openPromise = wrap(request);
    if (upgrade) {
      request.addEventListener("upgradeneeded", (event) => {
        upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event);
      });
    }
    if (blocked) {
      request.addEventListener("blocked", (event) => blocked(
        // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405
        event.oldVersion,
        event.newVersion,
        event
      ));
    }
    openPromise.then((db) => {
      if (terminated)
        db.addEventListener("close", () => terminated());
      if (blocking) {
        db.addEventListener("versionchange", (event) => blocking(event.oldVersion, event.newVersion, event));
      }
    }).catch(() => {
    });
    return openPromise;
  }
  const readMethods = ["get", "getKey", "getAll", "getAllKeys", "count"];
  const writeMethods = ["put", "add", "delete", "clear"];
  const cachedMethods = /* @__PURE__ */ new Map();
  function getMethod(target, prop) {
    if (!(target instanceof IDBDatabase && !(prop in target) && typeof prop === "string")) {
      return;
    }
    if (cachedMethods.get(prop))
      return cachedMethods.get(prop);
    const targetFuncName = prop.replace(/FromIndex$/, "");
    const useIndex = prop !== targetFuncName;
    const isWrite = writeMethods.includes(targetFuncName);
    if (
      // Bail if the target doesn't exist on the target. Eg, getAll isn't in Edge.
      !(targetFuncName in (useIndex ? IDBIndex : IDBObjectStore).prototype) || !(isWrite || readMethods.includes(targetFuncName))
    ) {
      return;
    }
    const method = async function(storeName, ...args) {
      const tx = this.transaction(storeName, isWrite ? "readwrite" : "readonly");
      let target2 = tx.store;
      if (useIndex)
        target2 = target2.index(args.shift());
      return (await Promise.all([
        target2[targetFuncName](...args),
        isWrite && tx.done
      ]))[0];
    };
    cachedMethods.set(prop, method);
    return method;
  }
  replaceTraps((oldTraps) => ({
    ...oldTraps,
    get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver),
    has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop)
  }));
  /**
   * @license
   * Copyright 2019 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class PlatformLoggerServiceImpl {
    constructor(container) {
      this.container = container;
    }
    // In initial implementation, this will be called by installations on
    // auth token refresh, and installations will send this string.
    getPlatformInfoString() {
      const providers = this.container.getProviders();
      return providers.map((provider) => {
        if (isVersionServiceProvider(provider)) {
          const service = provider.getImmediate();
          return `${service.library}/${service.version}`;
        } else {
          return null;
        }
      }).filter((logString) => logString).join(" ");
    }
  }
  function isVersionServiceProvider(provider) {
    const component = provider.getComponent();
    return (component === null || component === void 0 ? void 0 : component.type) === "VERSION";
  }
  const name$o = "@firebase/app";
  const version$1$1 = "0.9.15";
  /**
   * @license
   * Copyright 2019 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const logger$1 = new Logger2("@firebase/app");
  const name$n = "@firebase/app-compat";
  const name$m = "@firebase/analytics-compat";
  const name$l = "@firebase/analytics";
  const name$k = "@firebase/app-check-compat";
  const name$j = "@firebase/app-check";
  const name$i = "@firebase/auth";
  const name$h = "@firebase/auth-compat";
  const name$g = "@firebase/database";
  const name$f = "@firebase/database-compat";
  const name$e = "@firebase/functions";
  const name$d = "@firebase/functions-compat";
  const name$c = "@firebase/installations";
  const name$b = "@firebase/installations-compat";
  const name$a = "@firebase/messaging";
  const name$9 = "@firebase/messaging-compat";
  const name$8 = "@firebase/performance";
  const name$7 = "@firebase/performance-compat";
  const name$6 = "@firebase/remote-config";
  const name$5 = "@firebase/remote-config-compat";
  const name$4 = "@firebase/storage";
  const name$3 = "@firebase/storage-compat";
  const name$2 = "@firebase/firestore";
  const name$1$1 = "@firebase/firestore-compat";
  const name$p = "firebase";
  const version$2 = "10.1.0";
  /**
   * @license
   * Copyright 2019 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const DEFAULT_ENTRY_NAME = "[DEFAULT]";
  const PLATFORM_LOG_STRING = {
    [name$o]: "fire-core",
    [name$n]: "fire-core-compat",
    [name$l]: "fire-analytics",
    [name$m]: "fire-analytics-compat",
    [name$j]: "fire-app-check",
    [name$k]: "fire-app-check-compat",
    [name$i]: "fire-auth",
    [name$h]: "fire-auth-compat",
    [name$g]: "fire-rtdb",
    [name$f]: "fire-rtdb-compat",
    [name$e]: "fire-fn",
    [name$d]: "fire-fn-compat",
    [name$c]: "fire-iid",
    [name$b]: "fire-iid-compat",
    [name$a]: "fire-fcm",
    [name$9]: "fire-fcm-compat",
    [name$8]: "fire-perf",
    [name$7]: "fire-perf-compat",
    [name$6]: "fire-rc",
    [name$5]: "fire-rc-compat",
    [name$4]: "fire-gcs",
    [name$3]: "fire-gcs-compat",
    [name$2]: "fire-fst",
    [name$1$1]: "fire-fst-compat",
    "fire-js": "fire-js",
    [name$p]: "fire-js-all"
  };
  /**
   * @license
   * Copyright 2019 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const _apps = /* @__PURE__ */ new Map();
  const _components = /* @__PURE__ */ new Map();
  function _addComponent(app, component) {
    try {
      app.container.addComponent(component);
    } catch (e2) {
      logger$1.debug(`Component ${component.name} failed to register with FirebaseApp ${app.name}`, e2);
    }
  }
  function _registerComponent(component) {
    const componentName = component.name;
    if (_components.has(componentName)) {
      logger$1.debug(`There were multiple attempts to register component ${componentName}.`);
      return false;
    }
    _components.set(componentName, component);
    for (const app of _apps.values()) {
      _addComponent(app, component);
    }
    return true;
  }
  function _getProvider(app, name2) {
    const heartbeatController = app.container.getProvider("heartbeat").getImmediate({ optional: true });
    if (heartbeatController) {
      void heartbeatController.triggerHeartbeat();
    }
    return app.container.getProvider(name2);
  }
  /**
   * @license
   * Copyright 2019 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const ERRORS = {
    [
      "no-app"
      /* AppError.NO_APP */
    ]: "No Firebase App '{$appName}' has been created - call initializeApp() first",
    [
      "bad-app-name"
      /* AppError.BAD_APP_NAME */
    ]: "Illegal App name: '{$appName}",
    [
      "duplicate-app"
      /* AppError.DUPLICATE_APP */
    ]: "Firebase App named '{$appName}' already exists with different options or config",
    [
      "app-deleted"
      /* AppError.APP_DELETED */
    ]: "Firebase App named '{$appName}' already deleted",
    [
      "no-options"
      /* AppError.NO_OPTIONS */
    ]: "Need to provide options, when not being deployed to hosting via source.",
    [
      "invalid-app-argument"
      /* AppError.INVALID_APP_ARGUMENT */
    ]: "firebase.{$appName}() takes either no argument or a Firebase App instance.",
    [
      "invalid-log-argument"
      /* AppError.INVALID_LOG_ARGUMENT */
    ]: "First argument to `onLog` must be null or a function.",
    [
      "idb-open"
      /* AppError.IDB_OPEN */
    ]: "Error thrown when opening IndexedDB. Original error: {$originalErrorMessage}.",
    [
      "idb-get"
      /* AppError.IDB_GET */
    ]: "Error thrown when reading from IndexedDB. Original error: {$originalErrorMessage}.",
    [
      "idb-set"
      /* AppError.IDB_WRITE */
    ]: "Error thrown when writing to IndexedDB. Original error: {$originalErrorMessage}.",
    [
      "idb-delete"
      /* AppError.IDB_DELETE */
    ]: "Error thrown when deleting from IndexedDB. Original error: {$originalErrorMessage}."
  };
  const ERROR_FACTORY = new ErrorFactory("app", "Firebase", ERRORS);
  /**
   * @license
   * Copyright 2019 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class FirebaseAppImpl {
    constructor(options, config, container) {
      this._isDeleted = false;
      this._options = Object.assign({}, options);
      this._config = Object.assign({}, config);
      this._name = config.name;
      this._automaticDataCollectionEnabled = config.automaticDataCollectionEnabled;
      this._container = container;
      this.container.addComponent(new Component(
        "app",
        () => this,
        "PUBLIC"
        /* ComponentType.PUBLIC */
      ));
    }
    get automaticDataCollectionEnabled() {
      this.checkDestroyed();
      return this._automaticDataCollectionEnabled;
    }
    set automaticDataCollectionEnabled(val) {
      this.checkDestroyed();
      this._automaticDataCollectionEnabled = val;
    }
    get name() {
      this.checkDestroyed();
      return this._name;
    }
    get options() {
      this.checkDestroyed();
      return this._options;
    }
    get config() {
      this.checkDestroyed();
      return this._config;
    }
    get container() {
      return this._container;
    }
    get isDeleted() {
      return this._isDeleted;
    }
    set isDeleted(val) {
      this._isDeleted = val;
    }
    /**
     * This function will throw an Error if the App has already been deleted -
     * use before performing API actions on the App.
     */
    checkDestroyed() {
      if (this.isDeleted) {
        throw ERROR_FACTORY.create("app-deleted", { appName: this._name });
      }
    }
  }
  /**
   * @license
   * Copyright 2019 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const SDK_VERSION$1 = version$2;
  function initializeApp(_options, rawConfig = {}) {
    let options = _options;
    if (typeof rawConfig !== "object") {
      const name3 = rawConfig;
      rawConfig = { name: name3 };
    }
    const config = Object.assign({ name: DEFAULT_ENTRY_NAME, automaticDataCollectionEnabled: false }, rawConfig);
    const name2 = config.name;
    if (typeof name2 !== "string" || !name2) {
      throw ERROR_FACTORY.create("bad-app-name", {
        appName: String(name2)
      });
    }
    options || (options = getDefaultAppConfig());
    if (!options) {
      throw ERROR_FACTORY.create(
        "no-options"
        /* AppError.NO_OPTIONS */
      );
    }
    const existingApp = _apps.get(name2);
    if (existingApp) {
      if (deepEqual(options, existingApp.options) && deepEqual(config, existingApp.config)) {
        return existingApp;
      } else {
        throw ERROR_FACTORY.create("duplicate-app", { appName: name2 });
      }
    }
    const container = new ComponentContainer(name2);
    for (const component of _components.values()) {
      container.addComponent(component);
    }
    const newApp = new FirebaseAppImpl(options, config, container);
    _apps.set(name2, newApp);
    return newApp;
  }
  function getApp(name2 = DEFAULT_ENTRY_NAME) {
    const app = _apps.get(name2);
    if (!app && name2 === DEFAULT_ENTRY_NAME && getDefaultAppConfig()) {
      return initializeApp();
    }
    if (!app) {
      throw ERROR_FACTORY.create("no-app", { appName: name2 });
    }
    return app;
  }
  async function deleteApp(app) {
    const name2 = app.name;
    if (_apps.has(name2)) {
      _apps.delete(name2);
      await Promise.all(app.container.getProviders().map((provider) => provider.delete()));
      app.isDeleted = true;
    }
  }
  function registerVersion(libraryKeyOrName, version2, variant) {
    var _a2;
    let library = (_a2 = PLATFORM_LOG_STRING[libraryKeyOrName]) !== null && _a2 !== void 0 ? _a2 : libraryKeyOrName;
    if (variant) {
      library += `-${variant}`;
    }
    const libraryMismatch = library.match(/\s|\//);
    const versionMismatch = version2.match(/\s|\//);
    if (libraryMismatch || versionMismatch) {
      const warning = [
        `Unable to register library "${library}" with version "${version2}":`
      ];
      if (libraryMismatch) {
        warning.push(`library name "${library}" contains illegal characters (whitespace or "/")`);
      }
      if (libraryMismatch && versionMismatch) {
        warning.push("and");
      }
      if (versionMismatch) {
        warning.push(`version name "${version2}" contains illegal characters (whitespace or "/")`);
      }
      logger$1.warn(warning.join(" "));
      return;
    }
    _registerComponent(new Component(
      `${library}-version`,
      () => ({ library, version: version2 }),
      "VERSION"
      /* ComponentType.VERSION */
    ));
  }
  /**
   * @license
   * Copyright 2021 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const DB_NAME = "firebase-heartbeat-database";
  const DB_VERSION = 1;
  const STORE_NAME = "firebase-heartbeat-store";
  let dbPromise = null;
  function getDbPromise() {
    if (!dbPromise) {
      dbPromise = openDB(DB_NAME, DB_VERSION, {
        upgrade: (db, oldVersion) => {
          switch (oldVersion) {
            case 0:
              db.createObjectStore(STORE_NAME);
          }
        }
      }).catch((e2) => {
        throw ERROR_FACTORY.create("idb-open", {
          originalErrorMessage: e2.message
        });
      });
    }
    return dbPromise;
  }
  async function readHeartbeatsFromIndexedDB(app) {
    try {
      const db = await getDbPromise();
      const result = await db.transaction(STORE_NAME).objectStore(STORE_NAME).get(computeKey(app));
      return result;
    } catch (e2) {
      if (e2 instanceof FirebaseError) {
        logger$1.warn(e2.message);
      } else {
        const idbGetError = ERROR_FACTORY.create("idb-get", {
          originalErrorMessage: e2 === null || e2 === void 0 ? void 0 : e2.message
        });
        logger$1.warn(idbGetError.message);
      }
    }
  }
  async function writeHeartbeatsToIndexedDB(app, heartbeatObject) {
    try {
      const db = await getDbPromise();
      const tx = db.transaction(STORE_NAME, "readwrite");
      const objectStore = tx.objectStore(STORE_NAME);
      await objectStore.put(heartbeatObject, computeKey(app));
      await tx.done;
    } catch (e2) {
      if (e2 instanceof FirebaseError) {
        logger$1.warn(e2.message);
      } else {
        const idbGetError = ERROR_FACTORY.create("idb-set", {
          originalErrorMessage: e2 === null || e2 === void 0 ? void 0 : e2.message
        });
        logger$1.warn(idbGetError.message);
      }
    }
  }
  function computeKey(app) {
    return `${app.name}!${app.options.appId}`;
  }
  /**
   * @license
   * Copyright 2021 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const MAX_HEADER_BYTES = 1024;
  const STORED_HEARTBEAT_RETENTION_MAX_MILLIS = 30 * 24 * 60 * 60 * 1e3;
  class HeartbeatServiceImpl {
    constructor(container) {
      this.container = container;
      this._heartbeatsCache = null;
      const app = this.container.getProvider("app").getImmediate();
      this._storage = new HeartbeatStorageImpl(app);
      this._heartbeatsCachePromise = this._storage.read().then((result) => {
        this._heartbeatsCache = result;
        return result;
      });
    }
    /**
     * Called to report a heartbeat. The function will generate
     * a HeartbeatsByUserAgent object, update heartbeatsCache, and persist it
     * to IndexedDB.
     * Note that we only store one heartbeat per day. So if a heartbeat for today is
     * already logged, subsequent calls to this function in the same day will be ignored.
     */
    async triggerHeartbeat() {
      const platformLogger = this.container.getProvider("platform-logger").getImmediate();
      const agent = platformLogger.getPlatformInfoString();
      const date = getUTCDateString();
      if (this._heartbeatsCache === null) {
        this._heartbeatsCache = await this._heartbeatsCachePromise;
      }
      if (this._heartbeatsCache.lastSentHeartbeatDate === date || this._heartbeatsCache.heartbeats.some((singleDateHeartbeat) => singleDateHeartbeat.date === date)) {
        return;
      } else {
        this._heartbeatsCache.heartbeats.push({ date, agent });
      }
      this._heartbeatsCache.heartbeats = this._heartbeatsCache.heartbeats.filter((singleDateHeartbeat) => {
        const hbTimestamp = new Date(singleDateHeartbeat.date).valueOf();
        const now = Date.now();
        return now - hbTimestamp <= STORED_HEARTBEAT_RETENTION_MAX_MILLIS;
      });
      return this._storage.overwrite(this._heartbeatsCache);
    }
    /**
     * Returns a base64 encoded string which can be attached to the heartbeat-specific header directly.
     * It also clears all heartbeats from memory as well as in IndexedDB.
     *
     * NOTE: Consuming product SDKs should not send the header if this method
     * returns an empty string.
     */
    async getHeartbeatsHeader() {
      if (this._heartbeatsCache === null) {
        await this._heartbeatsCachePromise;
      }
      if (this._heartbeatsCache === null || this._heartbeatsCache.heartbeats.length === 0) {
        return "";
      }
      const date = getUTCDateString();
      const { heartbeatsToSend, unsentEntries } = extractHeartbeatsForHeader(this._heartbeatsCache.heartbeats);
      const headerString = base64urlEncodeWithoutPadding(JSON.stringify({ version: 2, heartbeats: heartbeatsToSend }));
      this._heartbeatsCache.lastSentHeartbeatDate = date;
      if (unsentEntries.length > 0) {
        this._heartbeatsCache.heartbeats = unsentEntries;
        await this._storage.overwrite(this._heartbeatsCache);
      } else {
        this._heartbeatsCache.heartbeats = [];
        void this._storage.overwrite(this._heartbeatsCache);
      }
      return headerString;
    }
  }
  function getUTCDateString() {
    const today = /* @__PURE__ */ new Date();
    return today.toISOString().substring(0, 10);
  }
  function extractHeartbeatsForHeader(heartbeatsCache, maxSize = MAX_HEADER_BYTES) {
    const heartbeatsToSend = [];
    let unsentEntries = heartbeatsCache.slice();
    for (const singleDateHeartbeat of heartbeatsCache) {
      const heartbeatEntry = heartbeatsToSend.find((hb) => hb.agent === singleDateHeartbeat.agent);
      if (!heartbeatEntry) {
        heartbeatsToSend.push({
          agent: singleDateHeartbeat.agent,
          dates: [singleDateHeartbeat.date]
        });
        if (countBytes(heartbeatsToSend) > maxSize) {
          heartbeatsToSend.pop();
          break;
        }
      } else {
        heartbeatEntry.dates.push(singleDateHeartbeat.date);
        if (countBytes(heartbeatsToSend) > maxSize) {
          heartbeatEntry.dates.pop();
          break;
        }
      }
      unsentEntries = unsentEntries.slice(1);
    }
    return {
      heartbeatsToSend,
      unsentEntries
    };
  }
  class HeartbeatStorageImpl {
    constructor(app) {
      this.app = app;
      this._canUseIndexedDBPromise = this.runIndexedDBEnvironmentCheck();
    }
    async runIndexedDBEnvironmentCheck() {
      if (!isIndexedDBAvailable()) {
        return false;
      } else {
        return validateIndexedDBOpenable().then(() => true).catch(() => false);
      }
    }
    /**
     * Read all heartbeats.
     */
    async read() {
      const canUseIndexedDB = await this._canUseIndexedDBPromise;
      if (!canUseIndexedDB) {
        return { heartbeats: [] };
      } else {
        const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app);
        return idbHeartbeatObject || { heartbeats: [] };
      }
    }
    // overwrite the storage with the provided heartbeats
    async overwrite(heartbeatsObject) {
      var _a2;
      const canUseIndexedDB = await this._canUseIndexedDBPromise;
      if (!canUseIndexedDB) {
        return;
      } else {
        const existingHeartbeatsObject = await this.read();
        return writeHeartbeatsToIndexedDB(this.app, {
          lastSentHeartbeatDate: (_a2 = heartbeatsObject.lastSentHeartbeatDate) !== null && _a2 !== void 0 ? _a2 : existingHeartbeatsObject.lastSentHeartbeatDate,
          heartbeats: heartbeatsObject.heartbeats
        });
      }
    }
    // add heartbeats
    async add(heartbeatsObject) {
      var _a2;
      const canUseIndexedDB = await this._canUseIndexedDBPromise;
      if (!canUseIndexedDB) {
        return;
      } else {
        const existingHeartbeatsObject = await this.read();
        return writeHeartbeatsToIndexedDB(this.app, {
          lastSentHeartbeatDate: (_a2 = heartbeatsObject.lastSentHeartbeatDate) !== null && _a2 !== void 0 ? _a2 : existingHeartbeatsObject.lastSentHeartbeatDate,
          heartbeats: [
            ...existingHeartbeatsObject.heartbeats,
            ...heartbeatsObject.heartbeats
          ]
        });
      }
    }
  }
  function countBytes(heartbeatsCache) {
    return base64urlEncodeWithoutPadding(
      // heartbeatsCache wrapper properties
      JSON.stringify({ version: 2, heartbeats: heartbeatsCache })
    ).length;
  }
  /**
   * @license
   * Copyright 2019 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function registerCoreComponents(variant) {
    _registerComponent(new Component(
      "platform-logger",
      (container) => new PlatformLoggerServiceImpl(container),
      "PRIVATE"
      /* ComponentType.PRIVATE */
    ));
    _registerComponent(new Component(
      "heartbeat",
      (container) => new HeartbeatServiceImpl(container),
      "PRIVATE"
      /* ComponentType.PRIVATE */
    ));
    registerVersion(name$o, version$1$1, variant);
    registerVersion(name$o, version$1$1, "esm2017");
    registerVersion("fire-js", "");
  }
  registerCoreComponents("");
  var name$1 = "firebase";
  var version$1 = "10.1.0";
  /**
   * @license
   * Copyright 2020 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  registerVersion(name$1, version$1, "app");
  const name = "@firebase/database";
  const version = "1.0.1";
  /**
   * @license
   * Copyright 2019 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  let SDK_VERSION = "";
  function setSDKVersion(version2) {
    SDK_VERSION = version2;
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class DOMStorageWrapper {
    /**
     * @param domStorage_ - The underlying storage object (e.g. localStorage or sessionStorage)
     */
    constructor(domStorage_) {
      this.domStorage_ = domStorage_;
      this.prefix_ = "firebase:";
    }
    /**
     * @param key - The key to save the value under
     * @param value - The value being stored, or null to remove the key.
     */
    set(key, value) {
      if (value == null) {
        this.domStorage_.removeItem(this.prefixedName_(key));
      } else {
        this.domStorage_.setItem(this.prefixedName_(key), stringify(value));
      }
    }
    /**
     * @returns The value that was stored under this key, or null
     */
    get(key) {
      const storedVal = this.domStorage_.getItem(this.prefixedName_(key));
      if (storedVal == null) {
        return null;
      } else {
        return jsonEval(storedVal);
      }
    }
    remove(key) {
      this.domStorage_.removeItem(this.prefixedName_(key));
    }
    prefixedName_(name2) {
      return this.prefix_ + name2;
    }
    toString() {
      return this.domStorage_.toString();
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class MemoryStorage {
    constructor() {
      this.cache_ = {};
      this.isInMemoryStorage = true;
    }
    set(key, value) {
      if (value == null) {
        delete this.cache_[key];
      } else {
        this.cache_[key] = value;
      }
    }
    get(key) {
      if (contains(this.cache_, key)) {
        return this.cache_[key];
      }
      return null;
    }
    remove(key) {
      delete this.cache_[key];
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const createStoragefor = function(domStorageName) {
    try {
      if (typeof window !== "undefined" && typeof window[domStorageName] !== "undefined") {
        const domStorage = window[domStorageName];
        domStorage.setItem("firebase:sentinel", "cache");
        domStorage.removeItem("firebase:sentinel");
        return new DOMStorageWrapper(domStorage);
      }
    } catch (e2) {
    }
    return new MemoryStorage();
  };
  const PersistentStorage = createStoragefor("localStorage");
  const SessionStorage = createStoragefor("sessionStorage");
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const logClient = new Logger2("@firebase/database");
  const LUIDGenerator = function() {
    let id = 1;
    return function() {
      return id++;
    };
  }();
  const sha1 = function(str) {
    const utf8Bytes = stringToByteArray(str);
    const sha12 = new Sha1();
    sha12.update(utf8Bytes);
    const sha1Bytes = sha12.digest();
    return base64.encodeByteArray(sha1Bytes);
  };
  const buildLogMessage_ = function(...varArgs) {
    let message = "";
    for (let i2 = 0; i2 < varArgs.length; i2++) {
      const arg = varArgs[i2];
      if (Array.isArray(arg) || arg && typeof arg === "object" && // eslint-disable-next-line @typescript-eslint/no-explicit-any
      typeof arg.length === "number") {
        message += buildLogMessage_.apply(null, arg);
      } else if (typeof arg === "object") {
        message += stringify(arg);
      } else {
        message += arg;
      }
      message += " ";
    }
    return message;
  };
  let logger = null;
  let firstLog_ = true;
  const enableLogging$1 = function(logger_, persistent) {
    assert(!persistent || logger_ === true || logger_ === false, "Can't turn on custom loggers persistently.");
    if (logger_ === true) {
      logClient.logLevel = LogLevel.VERBOSE;
      logger = logClient.log.bind(logClient);
      if (persistent) {
        SessionStorage.set("logging_enabled", true);
      }
    } else if (typeof logger_ === "function") {
      logger = logger_;
    } else {
      logger = null;
      SessionStorage.remove("logging_enabled");
    }
  };
  const log = function(...varArgs) {
    if (firstLog_ === true) {
      firstLog_ = false;
      if (logger === null && SessionStorage.get("logging_enabled") === true) {
        enableLogging$1(true);
      }
    }
    if (logger) {
      const message = buildLogMessage_.apply(null, varArgs);
      logger(message);
    }
  };
  const logWrapper = function(prefix) {
    return function(...varArgs) {
      log(prefix, ...varArgs);
    };
  };
  const error = function(...varArgs) {
    const message = "FIREBASE INTERNAL ERROR: " + buildLogMessage_(...varArgs);
    logClient.error(message);
  };
  const fatal = function(...varArgs) {
    const message = `FIREBASE FATAL ERROR: ${buildLogMessage_(...varArgs)}`;
    logClient.error(message);
    throw new Error(message);
  };
  const warn = function(...varArgs) {
    const message = "FIREBASE WARNING: " + buildLogMessage_(...varArgs);
    logClient.warn(message);
  };
  const warnIfPageIsSecure = function() {
    if (typeof window !== "undefined" && window.location && window.location.protocol && window.location.protocol.indexOf("https:") !== -1) {
      warn("Insecure Firebase access from a secure page. Please use https in calls to new Firebase().");
    }
  };
  const isInvalidJSONNumber = function(data) {
    return typeof data === "number" && (data !== data || // NaN
    data === Number.POSITIVE_INFINITY || data === Number.NEGATIVE_INFINITY);
  };
  const executeWhenDOMReady = function(fn2) {
    if (document.readyState === "complete") {
      fn2();
    } else {
      let called = false;
      const wrappedFn = function() {
        if (!document.body) {
          setTimeout(wrappedFn, Math.floor(10));
          return;
        }
        if (!called) {
          called = true;
          fn2();
        }
      };
      if (document.addEventListener) {
        document.addEventListener("DOMContentLoaded", wrappedFn, false);
        window.addEventListener("load", wrappedFn, false);
      } else if (document.attachEvent) {
        document.attachEvent("onreadystatechange", () => {
          if (document.readyState === "complete") {
            wrappedFn();
          }
        });
        window.attachEvent("onload", wrappedFn);
      }
    }
  };
  const MIN_NAME = "[MIN_NAME]";
  const MAX_NAME = "[MAX_NAME]";
  const nameCompare = function(a2, b2) {
    if (a2 === b2) {
      return 0;
    } else if (a2 === MIN_NAME || b2 === MAX_NAME) {
      return -1;
    } else if (b2 === MIN_NAME || a2 === MAX_NAME) {
      return 1;
    } else {
      const aAsInt = tryParseInt(a2), bAsInt = tryParseInt(b2);
      if (aAsInt !== null) {
        if (bAsInt !== null) {
          return aAsInt - bAsInt === 0 ? a2.length - b2.length : aAsInt - bAsInt;
        } else {
          return -1;
        }
      } else if (bAsInt !== null) {
        return 1;
      } else {
        return a2 < b2 ? -1 : 1;
      }
    }
  };
  const stringCompare = function(a2, b2) {
    if (a2 === b2) {
      return 0;
    } else if (a2 < b2) {
      return -1;
    } else {
      return 1;
    }
  };
  const requireKey = function(key, obj) {
    if (obj && key in obj) {
      return obj[key];
    } else {
      throw new Error("Missing required key (" + key + ") in object: " + stringify(obj));
    }
  };
  const ObjectToUniqueKey = function(obj) {
    if (typeof obj !== "object" || obj === null) {
      return stringify(obj);
    }
    const keys = [];
    for (const k2 in obj) {
      keys.push(k2);
    }
    keys.sort();
    let key = "{";
    for (let i2 = 0; i2 < keys.length; i2++) {
      if (i2 !== 0) {
        key += ",";
      }
      key += stringify(keys[i2]);
      key += ":";
      key += ObjectToUniqueKey(obj[keys[i2]]);
    }
    key += "}";
    return key;
  };
  const splitStringBySize = function(str, segsize) {
    const len = str.length;
    if (len <= segsize) {
      return [str];
    }
    const dataSegs = [];
    for (let c2 = 0; c2 < len; c2 += segsize) {
      if (c2 + segsize > len) {
        dataSegs.push(str.substring(c2, len));
      } else {
        dataSegs.push(str.substring(c2, c2 + segsize));
      }
    }
    return dataSegs;
  };
  function each(obj, fn2) {
    for (const key in obj) {
      if (obj.hasOwnProperty(key)) {
        fn2(key, obj[key]);
      }
    }
  }
  const doubleToIEEE754String = function(v2) {
    assert(!isInvalidJSONNumber(v2), "Invalid JSON number");
    const ebits = 11, fbits = 52;
    const bias = (1 << ebits - 1) - 1;
    let s2, e2, f2, ln2, i2;
    if (v2 === 0) {
      e2 = 0;
      f2 = 0;
      s2 = 1 / v2 === -Infinity ? 1 : 0;
    } else {
      s2 = v2 < 0;
      v2 = Math.abs(v2);
      if (v2 >= Math.pow(2, 1 - bias)) {
        ln2 = Math.min(Math.floor(Math.log(v2) / Math.LN2), bias);
        e2 = ln2 + bias;
        f2 = Math.round(v2 * Math.pow(2, fbits - ln2) - Math.pow(2, fbits));
      } else {
        e2 = 0;
        f2 = Math.round(v2 / Math.pow(2, 1 - bias - fbits));
      }
    }
    const bits = [];
    for (i2 = fbits; i2; i2 -= 1) {
      bits.push(f2 % 2 ? 1 : 0);
      f2 = Math.floor(f2 / 2);
    }
    for (i2 = ebits; i2; i2 -= 1) {
      bits.push(e2 % 2 ? 1 : 0);
      e2 = Math.floor(e2 / 2);
    }
    bits.push(s2 ? 1 : 0);
    bits.reverse();
    const str = bits.join("");
    let hexByteString = "";
    for (i2 = 0; i2 < 64; i2 += 8) {
      let hexByte = parseInt(str.substr(i2, 8), 2).toString(16);
      if (hexByte.length === 1) {
        hexByte = "0" + hexByte;
      }
      hexByteString = hexByteString + hexByte;
    }
    return hexByteString.toLowerCase();
  };
  const isChromeExtensionContentScript = function() {
    return !!(typeof window === "object" && window["chrome"] && window["chrome"]["extension"] && !/^chrome/.test(window.location.href));
  };
  const isWindowsStoreApp = function() {
    return typeof Windows === "object" && typeof Windows.UI === "object";
  };
  function errorForServerCode(code, query) {
    let reason = "Unknown Error";
    if (code === "too_big") {
      reason = "The data requested exceeds the maximum size that can be accessed with a single request.";
    } else if (code === "permission_denied") {
      reason = "Client doesn't have permission to access the desired data.";
    } else if (code === "unavailable") {
      reason = "The service is unavailable";
    }
    const error2 = new Error(code + " at " + query._path.toString() + ": " + reason);
    error2.code = code.toUpperCase();
    return error2;
  }
  const INTEGER_REGEXP_ = new RegExp("^-?(0*)\\d{1,10}$");
  const INTEGER_32_MIN = -2147483648;
  const INTEGER_32_MAX = 2147483647;
  const tryParseInt = function(str) {
    if (INTEGER_REGEXP_.test(str)) {
      const intVal = Number(str);
      if (intVal >= INTEGER_32_MIN && intVal <= INTEGER_32_MAX) {
        return intVal;
      }
    }
    return null;
  };
  const exceptionGuard = function(fn2) {
    try {
      fn2();
    } catch (e2) {
      setTimeout(() => {
        const stack = e2.stack || "";
        warn("Exception was thrown by user callback.", stack);
        throw e2;
      }, Math.floor(0));
    }
  };
  const beingCrawled = function() {
    const userAgent = typeof window === "object" && window["navigator"] && window["navigator"]["userAgent"] || "";
    return userAgent.search(/googlebot|google webmaster tools|bingbot|yahoo! slurp|baiduspider|yandexbot|duckduckbot/i) >= 0;
  };
  const setTimeoutNonBlocking = function(fn2, time) {
    const timeout = setTimeout(fn2, time);
    if (typeof timeout === "number" && // @ts-ignore Is only defined in Deno environments.
    typeof Deno !== "undefined" && // @ts-ignore Deno and unrefTimer are only defined in Deno environments.
    Deno["unrefTimer"]) {
      Deno.unrefTimer(timeout);
    } else if (typeof timeout === "object" && timeout["unref"]) {
      timeout["unref"]();
    }
    return timeout;
  };
  /**
   * @license
   * Copyright 2021 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class AppCheckTokenProvider {
    constructor(appName_, appCheckProvider) {
      this.appName_ = appName_;
      this.appCheckProvider = appCheckProvider;
      this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
      if (!this.appCheck) {
        appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then((appCheck) => this.appCheck = appCheck);
      }
    }
    getToken(forceRefresh) {
      if (!this.appCheck) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            if (this.appCheck) {
              this.getToken(forceRefresh).then(resolve, reject);
            } else {
              resolve(null);
            }
          }, 0);
        });
      }
      return this.appCheck.getToken(forceRefresh);
    }
    addTokenChangeListener(listener) {
      var _a2;
      (_a2 = this.appCheckProvider) === null || _a2 === void 0 ? void 0 : _a2.get().then((appCheck) => appCheck.addTokenListener(listener));
    }
    notifyForInvalidToken() {
      warn(`Provided AppCheck credentials for the app named "${this.appName_}" are invalid. This usually indicates your app was not initialized correctly.`);
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class FirebaseAuthTokenProvider {
    constructor(appName_, firebaseOptions_, authProvider_) {
      this.appName_ = appName_;
      this.firebaseOptions_ = firebaseOptions_;
      this.authProvider_ = authProvider_;
      this.auth_ = null;
      this.auth_ = authProvider_.getImmediate({ optional: true });
      if (!this.auth_) {
        authProvider_.onInit((auth) => this.auth_ = auth);
      }
    }
    getToken(forceRefresh) {
      if (!this.auth_) {
        return new Promise((resolve, reject) => {
          setTimeout(() => {
            if (this.auth_) {
              this.getToken(forceRefresh).then(resolve, reject);
            } else {
              resolve(null);
            }
          }, 0);
        });
      }
      return this.auth_.getToken(forceRefresh).catch((error2) => {
        if (error2 && error2.code === "auth/token-not-initialized") {
          log("Got auth/token-not-initialized error.  Treating as null token.");
          return null;
        } else {
          return Promise.reject(error2);
        }
      });
    }
    addTokenChangeListener(listener) {
      if (this.auth_) {
        this.auth_.addAuthTokenListener(listener);
      } else {
        this.authProvider_.get().then((auth) => auth.addAuthTokenListener(listener));
      }
    }
    removeTokenChangeListener(listener) {
      this.authProvider_.get().then((auth) => auth.removeAuthTokenListener(listener));
    }
    notifyForInvalidToken() {
      let errorMessage = 'Provided authentication credentials for the app named "' + this.appName_ + '" are invalid. This usually indicates your app was not initialized correctly. ';
      if ("credential" in this.firebaseOptions_) {
        errorMessage += 'Make sure the "credential" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.';
      } else if ("serviceAccount" in this.firebaseOptions_) {
        errorMessage += 'Make sure the "serviceAccount" property provided to initializeApp() is authorized to access the specified "databaseURL" and is from the correct project.';
      } else {
        errorMessage += 'Make sure the "apiKey" and "databaseURL" properties provided to initializeApp() match the values provided for your app at https://console.firebase.google.com/.';
      }
      warn(errorMessage);
    }
  }
  class EmulatorTokenProvider {
    constructor(accessToken) {
      this.accessToken = accessToken;
    }
    getToken(forceRefresh) {
      return Promise.resolve({
        accessToken: this.accessToken
      });
    }
    addTokenChangeListener(listener) {
      listener(this.accessToken);
    }
    removeTokenChangeListener(listener) {
    }
    notifyForInvalidToken() {
    }
  }
  EmulatorTokenProvider.OWNER = "owner";
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const PROTOCOL_VERSION = "5";
  const VERSION_PARAM = "v";
  const TRANSPORT_SESSION_PARAM = "s";
  const REFERER_PARAM = "r";
  const FORGE_REF = "f";
  const FORGE_DOMAIN_RE = /(console\.firebase|firebase-console-\w+\.corp|firebase\.corp)\.google\.com/;
  const LAST_SESSION_PARAM = "ls";
  const APPLICATION_ID_PARAM = "p";
  const APP_CHECK_TOKEN_PARAM = "ac";
  const WEBSOCKET = "websocket";
  const LONG_POLLING = "long_polling";
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class RepoInfo {
    /**
     * @param host - Hostname portion of the url for the repo
     * @param secure - Whether or not this repo is accessed over ssl
     * @param namespace - The namespace represented by the repo
     * @param webSocketOnly - Whether to prefer websockets over all other transports (used by Nest).
     * @param nodeAdmin - Whether this instance uses Admin SDK credentials
     * @param persistenceKey - Override the default session persistence storage key
     */
    constructor(host, secure, namespace, webSocketOnly, nodeAdmin = false, persistenceKey = "", includeNamespaceInQueryParams = false, isUsingEmulator = false) {
      this.secure = secure;
      this.namespace = namespace;
      this.webSocketOnly = webSocketOnly;
      this.nodeAdmin = nodeAdmin;
      this.persistenceKey = persistenceKey;
      this.includeNamespaceInQueryParams = includeNamespaceInQueryParams;
      this.isUsingEmulator = isUsingEmulator;
      this._host = host.toLowerCase();
      this._domain = this._host.substr(this._host.indexOf(".") + 1);
      this.internalHost = PersistentStorage.get("host:" + host) || this._host;
    }
    isCacheableHost() {
      return this.internalHost.substr(0, 2) === "s-";
    }
    isCustomHost() {
      return this._domain !== "firebaseio.com" && this._domain !== "firebaseio-demo.com";
    }
    get host() {
      return this._host;
    }
    set host(newHost) {
      if (newHost !== this.internalHost) {
        this.internalHost = newHost;
        if (this.isCacheableHost()) {
          PersistentStorage.set("host:" + this._host, this.internalHost);
        }
      }
    }
    toString() {
      let str = this.toURLString();
      if (this.persistenceKey) {
        str += "<" + this.persistenceKey + ">";
      }
      return str;
    }
    toURLString() {
      const protocol = this.secure ? "https://" : "http://";
      const query = this.includeNamespaceInQueryParams ? `?ns=${this.namespace}` : "";
      return `${protocol}${this.host}/${query}`;
    }
  }
  function repoInfoNeedsQueryParam(repoInfo) {
    return repoInfo.host !== repoInfo.internalHost || repoInfo.isCustomHost() || repoInfo.includeNamespaceInQueryParams;
  }
  function repoInfoConnectionURL(repoInfo, type, params) {
    assert(typeof type === "string", "typeof type must == string");
    assert(typeof params === "object", "typeof params must == object");
    let connURL;
    if (type === WEBSOCKET) {
      connURL = (repoInfo.secure ? "wss://" : "ws://") + repoInfo.internalHost + "/.ws?";
    } else if (type === LONG_POLLING) {
      connURL = (repoInfo.secure ? "https://" : "http://") + repoInfo.internalHost + "/.lp?";
    } else {
      throw new Error("Unknown connection type: " + type);
    }
    if (repoInfoNeedsQueryParam(repoInfo)) {
      params["ns"] = repoInfo.namespace;
    }
    const pairs = [];
    each(params, (key, value) => {
      pairs.push(key + "=" + value);
    });
    return connURL + pairs.join("&");
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class StatsCollection {
    constructor() {
      this.counters_ = {};
    }
    incrementCounter(name2, amount = 1) {
      if (!contains(this.counters_, name2)) {
        this.counters_[name2] = 0;
      }
      this.counters_[name2] += amount;
    }
    get() {
      return deepCopy(this.counters_);
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const collections = {};
  const reporters = {};
  function statsManagerGetCollection(repoInfo) {
    const hashString = repoInfo.toString();
    if (!collections[hashString]) {
      collections[hashString] = new StatsCollection();
    }
    return collections[hashString];
  }
  function statsManagerGetOrCreateReporter(repoInfo, creatorFunction) {
    const hashString = repoInfo.toString();
    if (!reporters[hashString]) {
      reporters[hashString] = creatorFunction();
    }
    return reporters[hashString];
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class PacketReceiver {
    /**
     * @param onMessage_
     */
    constructor(onMessage_) {
      this.onMessage_ = onMessage_;
      this.pendingResponses = [];
      this.currentResponseNum = 0;
      this.closeAfterResponse = -1;
      this.onClose = null;
    }
    closeAfter(responseNum, callback) {
      this.closeAfterResponse = responseNum;
      this.onClose = callback;
      if (this.closeAfterResponse < this.currentResponseNum) {
        this.onClose();
        this.onClose = null;
      }
    }
    /**
     * Each message from the server comes with a response number, and an array of data. The responseNumber
     * allows us to ensure that we process them in the right order, since we can't be guaranteed that all
     * browsers will respond in the same order as the requests we sent
     */
    handleResponse(requestNum, data) {
      this.pendingResponses[requestNum] = data;
      while (this.pendingResponses[this.currentResponseNum]) {
        const toProcess = this.pendingResponses[this.currentResponseNum];
        delete this.pendingResponses[this.currentResponseNum];
        for (let i2 = 0; i2 < toProcess.length; ++i2) {
          if (toProcess[i2]) {
            exceptionGuard(() => {
              this.onMessage_(toProcess[i2]);
            });
          }
        }
        if (this.currentResponseNum === this.closeAfterResponse) {
          if (this.onClose) {
            this.onClose();
            this.onClose = null;
          }
          break;
        }
        this.currentResponseNum++;
      }
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const FIREBASE_LONGPOLL_START_PARAM = "start";
  const FIREBASE_LONGPOLL_CLOSE_COMMAND = "close";
  const FIREBASE_LONGPOLL_COMMAND_CB_NAME = "pLPCommand";
  const FIREBASE_LONGPOLL_DATA_CB_NAME = "pRTLPCB";
  const FIREBASE_LONGPOLL_ID_PARAM = "id";
  const FIREBASE_LONGPOLL_PW_PARAM = "pw";
  const FIREBASE_LONGPOLL_SERIAL_PARAM = "ser";
  const FIREBASE_LONGPOLL_CALLBACK_ID_PARAM = "cb";
  const FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM = "seg";
  const FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET = "ts";
  const FIREBASE_LONGPOLL_DATA_PARAM = "d";
  const FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM = "dframe";
  const MAX_URL_DATA_SIZE = 1870;
  const SEG_HEADER_SIZE = 30;
  const MAX_PAYLOAD_SIZE = MAX_URL_DATA_SIZE - SEG_HEADER_SIZE;
  const KEEPALIVE_REQUEST_INTERVAL = 25e3;
  const LP_CONNECT_TIMEOUT = 3e4;
  class BrowserPollConnection {
    /**
     * @param connId An identifier for this connection, used for logging
     * @param repoInfo The info for the endpoint to send data to.
     * @param applicationId The Firebase App ID for this project.
     * @param appCheckToken The AppCheck token for this client.
     * @param authToken The AuthToken to use for this connection.
     * @param transportSessionId Optional transportSessionid if we are
     * reconnecting for an existing transport session
     * @param lastSessionId Optional lastSessionId if the PersistentConnection has
     * already created a connection previously
     */
    constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
      this.connId = connId;
      this.repoInfo = repoInfo;
      this.applicationId = applicationId;
      this.appCheckToken = appCheckToken;
      this.authToken = authToken;
      this.transportSessionId = transportSessionId;
      this.lastSessionId = lastSessionId;
      this.bytesSent = 0;
      this.bytesReceived = 0;
      this.everConnected_ = false;
      this.log_ = logWrapper(connId);
      this.stats_ = statsManagerGetCollection(repoInfo);
      this.urlFn = (params) => {
        if (this.appCheckToken) {
          params[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
        }
        return repoInfoConnectionURL(repoInfo, LONG_POLLING, params);
      };
    }
    /**
     * @param onMessage - Callback when messages arrive
     * @param onDisconnect - Callback with connection lost.
     */
    open(onMessage, onDisconnect) {
      this.curSegmentNum = 0;
      this.onDisconnect_ = onDisconnect;
      this.myPacketOrderer = new PacketReceiver(onMessage);
      this.isClosed_ = false;
      this.connectTimeoutTimer_ = setTimeout(() => {
        this.log_("Timed out trying to connect.");
        this.onClosed_();
        this.connectTimeoutTimer_ = null;
      }, Math.floor(LP_CONNECT_TIMEOUT));
      executeWhenDOMReady(() => {
        if (this.isClosed_) {
          return;
        }
        this.scriptTagHolder = new FirebaseIFrameScriptHolder((...args) => {
          const [command, arg1, arg2, arg3, arg4] = args;
          this.incrementIncomingBytes_(args);
          if (!this.scriptTagHolder) {
            return;
          }
          if (this.connectTimeoutTimer_) {
            clearTimeout(this.connectTimeoutTimer_);
            this.connectTimeoutTimer_ = null;
          }
          this.everConnected_ = true;
          if (command === FIREBASE_LONGPOLL_START_PARAM) {
            this.id = arg1;
            this.password = arg2;
          } else if (command === FIREBASE_LONGPOLL_CLOSE_COMMAND) {
            if (arg1) {
              this.scriptTagHolder.sendNewPolls = false;
              this.myPacketOrderer.closeAfter(arg1, () => {
                this.onClosed_();
              });
            } else {
              this.onClosed_();
            }
          } else {
            throw new Error("Unrecognized command received: " + command);
          }
        }, (...args) => {
          const [pN, data] = args;
          this.incrementIncomingBytes_(args);
          this.myPacketOrderer.handleResponse(pN, data);
        }, () => {
          this.onClosed_();
        }, this.urlFn);
        const urlParams = {};
        urlParams[FIREBASE_LONGPOLL_START_PARAM] = "t";
        urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = Math.floor(Math.random() * 1e8);
        if (this.scriptTagHolder.uniqueCallbackIdentifier) {
          urlParams[FIREBASE_LONGPOLL_CALLBACK_ID_PARAM] = this.scriptTagHolder.uniqueCallbackIdentifier;
        }
        urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
        if (this.transportSessionId) {
          urlParams[TRANSPORT_SESSION_PARAM] = this.transportSessionId;
        }
        if (this.lastSessionId) {
          urlParams[LAST_SESSION_PARAM] = this.lastSessionId;
        }
        if (this.applicationId) {
          urlParams[APPLICATION_ID_PARAM] = this.applicationId;
        }
        if (this.appCheckToken) {
          urlParams[APP_CHECK_TOKEN_PARAM] = this.appCheckToken;
        }
        if (typeof location !== "undefined" && location.hostname && FORGE_DOMAIN_RE.test(location.hostname)) {
          urlParams[REFERER_PARAM] = FORGE_REF;
        }
        const connectURL = this.urlFn(urlParams);
        this.log_("Connecting via long-poll to " + connectURL);
        this.scriptTagHolder.addTag(connectURL, () => {
        });
      });
    }
    /**
     * Call this when a handshake has completed successfully and we want to consider the connection established
     */
    start() {
      this.scriptTagHolder.startLongPoll(this.id, this.password);
      this.addDisconnectPingFrame(this.id, this.password);
    }
    /**
     * Forces long polling to be considered as a potential transport
     */
    static forceAllow() {
      BrowserPollConnection.forceAllow_ = true;
    }
    /**
     * Forces longpolling to not be considered as a potential transport
     */
    static forceDisallow() {
      BrowserPollConnection.forceDisallow_ = true;
    }
    // Static method, use string literal so it can be accessed in a generic way
    static isAvailable() {
      if (BrowserPollConnection.forceAllow_) {
        return true;
      } else {
        return !BrowserPollConnection.forceDisallow_ && typeof document !== "undefined" && document.createElement != null && !isChromeExtensionContentScript() && !isWindowsStoreApp();
      }
    }
    /**
     * No-op for polling
     */
    markConnectionHealthy() {
    }
    /**
     * Stops polling and cleans up the iframe
     */
    shutdown_() {
      this.isClosed_ = true;
      if (this.scriptTagHolder) {
        this.scriptTagHolder.close();
        this.scriptTagHolder = null;
      }
      if (this.myDisconnFrame) {
        document.body.removeChild(this.myDisconnFrame);
        this.myDisconnFrame = null;
      }
      if (this.connectTimeoutTimer_) {
        clearTimeout(this.connectTimeoutTimer_);
        this.connectTimeoutTimer_ = null;
      }
    }
    /**
     * Triggered when this transport is closed
     */
    onClosed_() {
      if (!this.isClosed_) {
        this.log_("Longpoll is closing itself");
        this.shutdown_();
        if (this.onDisconnect_) {
          this.onDisconnect_(this.everConnected_);
          this.onDisconnect_ = null;
        }
      }
    }
    /**
     * External-facing close handler. RealTime has requested we shut down. Kill our connection and tell the server
     * that we've left.
     */
    close() {
      if (!this.isClosed_) {
        this.log_("Longpoll is being closed.");
        this.shutdown_();
      }
    }
    /**
     * Send the JSON object down to the server. It will need to be stringified, base64 encoded, and then
     * broken into chunks (since URLs have a small maximum length).
     * @param data - The JSON data to transmit.
     */
    send(data) {
      const dataStr = stringify(data);
      this.bytesSent += dataStr.length;
      this.stats_.incrementCounter("bytes_sent", dataStr.length);
      const base64data = base64Encode(dataStr);
      const dataSegs = splitStringBySize(base64data, MAX_PAYLOAD_SIZE);
      for (let i2 = 0; i2 < dataSegs.length; i2++) {
        this.scriptTagHolder.enqueueSegment(this.curSegmentNum, dataSegs.length, dataSegs[i2]);
        this.curSegmentNum++;
      }
    }
    /**
     * This is how we notify the server that we're leaving.
     * We aren't able to send requests with DHTML on a window close event, but we can
     * trigger XHR requests in some browsers (everything but Opera basically).
     */
    addDisconnectPingFrame(id, pw) {
      this.myDisconnFrame = document.createElement("iframe");
      const urlParams = {};
      urlParams[FIREBASE_LONGPOLL_DISCONN_FRAME_REQUEST_PARAM] = "t";
      urlParams[FIREBASE_LONGPOLL_ID_PARAM] = id;
      urlParams[FIREBASE_LONGPOLL_PW_PARAM] = pw;
      this.myDisconnFrame.src = this.urlFn(urlParams);
      this.myDisconnFrame.style.display = "none";
      document.body.appendChild(this.myDisconnFrame);
    }
    /**
     * Used to track the bytes received by this client
     */
    incrementIncomingBytes_(args) {
      const bytesReceived = stringify(args).length;
      this.bytesReceived += bytesReceived;
      this.stats_.incrementCounter("bytes_received", bytesReceived);
    }
  }
  class FirebaseIFrameScriptHolder {
    /**
     * @param commandCB - The callback to be called when control commands are recevied from the server.
     * @param onMessageCB - The callback to be triggered when responses arrive from the server.
     * @param onDisconnect - The callback to be triggered when this tag holder is closed
     * @param urlFn - A function that provides the URL of the endpoint to send data to.
     */
    constructor(commandCB, onMessageCB, onDisconnect, urlFn) {
      this.onDisconnect = onDisconnect;
      this.urlFn = urlFn;
      this.outstandingRequests = /* @__PURE__ */ new Set();
      this.pendingSegs = [];
      this.currentSerial = Math.floor(Math.random() * 1e8);
      this.sendNewPolls = true;
      {
        this.uniqueCallbackIdentifier = LUIDGenerator();
        window[FIREBASE_LONGPOLL_COMMAND_CB_NAME + this.uniqueCallbackIdentifier] = commandCB;
        window[FIREBASE_LONGPOLL_DATA_CB_NAME + this.uniqueCallbackIdentifier] = onMessageCB;
        this.myIFrame = FirebaseIFrameScriptHolder.createIFrame_();
        let script = "";
        if (this.myIFrame.src && this.myIFrame.src.substr(0, "javascript:".length) === "javascript:") {
          const currentDomain = document.domain;
          script = '<script>document.domain="' + currentDomain + '";<\/script>';
        }
        const iframeContents = "<html><body>" + script + "</body></html>";
        try {
          this.myIFrame.doc.open();
          this.myIFrame.doc.write(iframeContents);
          this.myIFrame.doc.close();
        } catch (e2) {
          log("frame writing exception");
          if (e2.stack) {
            log(e2.stack);
          }
          log(e2);
        }
      }
    }
    /**
     * Each browser has its own funny way to handle iframes. Here we mush them all together into one object that I can
     * actually use.
     */
    static createIFrame_() {
      const iframe = document.createElement("iframe");
      iframe.style.display = "none";
      if (document.body) {
        document.body.appendChild(iframe);
        try {
          const a2 = iframe.contentWindow.document;
          if (!a2) {
            log("No IE domain setting required");
          }
        } catch (e2) {
          const domain = document.domain;
          iframe.src = "javascript:void((function(){document.open();document.domain='" + domain + "';document.close();})())";
        }
      } else {
        throw "Document body has not initialized. Wait to initialize Firebase until after the document is ready.";
      }
      if (iframe.contentDocument) {
        iframe.doc = iframe.contentDocument;
      } else if (iframe.contentWindow) {
        iframe.doc = iframe.contentWindow.document;
      } else if (iframe.document) {
        iframe.doc = iframe.document;
      }
      return iframe;
    }
    /**
     * Cancel all outstanding queries and remove the frame.
     */
    close() {
      this.alive = false;
      if (this.myIFrame) {
        this.myIFrame.doc.body.textContent = "";
        setTimeout(() => {
          if (this.myIFrame !== null) {
            document.body.removeChild(this.myIFrame);
            this.myIFrame = null;
          }
        }, Math.floor(0));
      }
      const onDisconnect = this.onDisconnect;
      if (onDisconnect) {
        this.onDisconnect = null;
        onDisconnect();
      }
    }
    /**
     * Actually start the long-polling session by adding the first script tag(s) to the iframe.
     * @param id - The ID of this connection
     * @param pw - The password for this connection
     */
    startLongPoll(id, pw) {
      this.myID = id;
      this.myPW = pw;
      this.alive = true;
      while (this.newRequest_()) {
      }
    }
    /**
     * This is called any time someone might want a script tag to be added. It adds a script tag when there aren't
     * too many outstanding requests and we are still alive.
     *
     * If there are outstanding packet segments to send, it sends one. If there aren't, it sends a long-poll anyways if
     * needed.
     */
    newRequest_() {
      if (this.alive && this.sendNewPolls && this.outstandingRequests.size < (this.pendingSegs.length > 0 ? 2 : 1)) {
        this.currentSerial++;
        const urlParams = {};
        urlParams[FIREBASE_LONGPOLL_ID_PARAM] = this.myID;
        urlParams[FIREBASE_LONGPOLL_PW_PARAM] = this.myPW;
        urlParams[FIREBASE_LONGPOLL_SERIAL_PARAM] = this.currentSerial;
        let theURL = this.urlFn(urlParams);
        let curDataString = "";
        let i2 = 0;
        while (this.pendingSegs.length > 0) {
          const nextSeg = this.pendingSegs[0];
          if (nextSeg.d.length + SEG_HEADER_SIZE + curDataString.length <= MAX_URL_DATA_SIZE) {
            const theSeg = this.pendingSegs.shift();
            curDataString = curDataString + "&" + FIREBASE_LONGPOLL_SEGMENT_NUM_PARAM + i2 + "=" + theSeg.seg + "&" + FIREBASE_LONGPOLL_SEGMENTS_IN_PACKET + i2 + "=" + theSeg.ts + "&" + FIREBASE_LONGPOLL_DATA_PARAM + i2 + "=" + theSeg.d;
            i2++;
          } else {
            break;
          }
        }
        theURL = theURL + curDataString;
        this.addLongPollTag_(theURL, this.currentSerial);
        return true;
      } else {
        return false;
      }
    }
    /**
     * Queue a packet for transmission to the server.
     * @param segnum - A sequential id for this packet segment used for reassembly
     * @param totalsegs - The total number of segments in this packet
     * @param data - The data for this segment.
     */
    enqueueSegment(segnum, totalsegs, data) {
      this.pendingSegs.push({ seg: segnum, ts: totalsegs, d: data });
      if (this.alive) {
        this.newRequest_();
      }
    }
    /**
     * Add a script tag for a regular long-poll request.
     * @param url - The URL of the script tag.
     * @param serial - The serial number of the request.
     */
    addLongPollTag_(url, serial) {
      this.outstandingRequests.add(serial);
      const doNewRequest = () => {
        this.outstandingRequests.delete(serial);
        this.newRequest_();
      };
      const keepaliveTimeout = setTimeout(doNewRequest, Math.floor(KEEPALIVE_REQUEST_INTERVAL));
      const readyStateCB = () => {
        clearTimeout(keepaliveTimeout);
        doNewRequest();
      };
      this.addTag(url, readyStateCB);
    }
    /**
     * Add an arbitrary script tag to the iframe.
     * @param url - The URL for the script tag source.
     * @param loadCB - A callback to be triggered once the script has loaded.
     */
    addTag(url, loadCB) {
      {
        setTimeout(() => {
          try {
            if (!this.sendNewPolls) {
              return;
            }
            const newScript = this.myIFrame.doc.createElement("script");
            newScript.type = "text/javascript";
            newScript.async = true;
            newScript.src = url;
            newScript.onload = newScript.onreadystatechange = function() {
              const rstate = newScript.readyState;
              if (!rstate || rstate === "loaded" || rstate === "complete") {
                newScript.onload = newScript.onreadystatechange = null;
                if (newScript.parentNode) {
                  newScript.parentNode.removeChild(newScript);
                }
                loadCB();
              }
            };
            newScript.onerror = () => {
              log("Long-poll script failed to load: " + url);
              this.sendNewPolls = false;
              this.close();
            };
            this.myIFrame.doc.body.appendChild(newScript);
          } catch (e2) {
          }
        }, Math.floor(1));
      }
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const WEBSOCKET_MAX_FRAME_SIZE = 16384;
  const WEBSOCKET_KEEPALIVE_INTERVAL = 45e3;
  let WebSocketImpl = null;
  if (typeof MozWebSocket !== "undefined") {
    WebSocketImpl = MozWebSocket;
  } else if (typeof WebSocket !== "undefined") {
    WebSocketImpl = WebSocket;
  }
  class WebSocketConnection {
    /**
     * @param connId identifier for this transport
     * @param repoInfo The info for the websocket endpoint.
     * @param applicationId The Firebase App ID for this project.
     * @param appCheckToken The App Check Token for this client.
     * @param authToken The Auth Token for this client.
     * @param transportSessionId Optional transportSessionId if this is connecting
     * to an existing transport session
     * @param lastSessionId Optional lastSessionId if there was a previous
     * connection
     */
    constructor(connId, repoInfo, applicationId, appCheckToken, authToken, transportSessionId, lastSessionId) {
      this.connId = connId;
      this.applicationId = applicationId;
      this.appCheckToken = appCheckToken;
      this.authToken = authToken;
      this.keepaliveTimer = null;
      this.frames = null;
      this.totalFrames = 0;
      this.bytesSent = 0;
      this.bytesReceived = 0;
      this.log_ = logWrapper(this.connId);
      this.stats_ = statsManagerGetCollection(repoInfo);
      this.connURL = WebSocketConnection.connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId);
      this.nodeAdmin = repoInfo.nodeAdmin;
    }
    /**
     * @param repoInfo - The info for the websocket endpoint.
     * @param transportSessionId - Optional transportSessionId if this is connecting to an existing transport
     *                                         session
     * @param lastSessionId - Optional lastSessionId if there was a previous connection
     * @returns connection url
     */
    static connectionURL_(repoInfo, transportSessionId, lastSessionId, appCheckToken, applicationId) {
      const urlParams = {};
      urlParams[VERSION_PARAM] = PROTOCOL_VERSION;
      if (typeof location !== "undefined" && location.hostname && FORGE_DOMAIN_RE.test(location.hostname)) {
        urlParams[REFERER_PARAM] = FORGE_REF;
      }
      if (transportSessionId) {
        urlParams[TRANSPORT_SESSION_PARAM] = transportSessionId;
      }
      if (lastSessionId) {
        urlParams[LAST_SESSION_PARAM] = lastSessionId;
      }
      if (appCheckToken) {
        urlParams[APP_CHECK_TOKEN_PARAM] = appCheckToken;
      }
      if (applicationId) {
        urlParams[APPLICATION_ID_PARAM] = applicationId;
      }
      return repoInfoConnectionURL(repoInfo, WEBSOCKET, urlParams);
    }
    /**
     * @param onMessage - Callback when messages arrive
     * @param onDisconnect - Callback with connection lost.
     */
    open(onMessage, onDisconnect) {
      this.onDisconnect = onDisconnect;
      this.onMessage = onMessage;
      this.log_("Websocket connecting to " + this.connURL);
      this.everConnected_ = false;
      PersistentStorage.set("previous_websocket_failure", true);
      try {
        let options;
        if (isNodeSdk())
          ;
        this.mySock = new WebSocketImpl(this.connURL, [], options);
      } catch (e2) {
        this.log_("Error instantiating WebSocket.");
        const error2 = e2.message || e2.data;
        if (error2) {
          this.log_(error2);
        }
        this.onClosed_();
        return;
      }
      this.mySock.onopen = () => {
        this.log_("Websocket connected.");
        this.everConnected_ = true;
      };
      this.mySock.onclose = () => {
        this.log_("Websocket connection was disconnected.");
        this.mySock = null;
        this.onClosed_();
      };
      this.mySock.onmessage = (m2) => {
        this.handleIncomingFrame(m2);
      };
      this.mySock.onerror = (e2) => {
        this.log_("WebSocket error.  Closing connection.");
        const error2 = e2.message || e2.data;
        if (error2) {
          this.log_(error2);
        }
        this.onClosed_();
      };
    }
    /**
     * No-op for websockets, we don't need to do anything once the connection is confirmed as open
     */
    start() {
    }
    static forceDisallow() {
      WebSocketConnection.forceDisallow_ = true;
    }
    static isAvailable() {
      let isOldAndroid = false;
      if (typeof navigator !== "undefined" && navigator.userAgent) {
        const oldAndroidRegex = /Android ([0-9]{0,}\.[0-9]{0,})/;
        const oldAndroidMatch = navigator.userAgent.match(oldAndroidRegex);
        if (oldAndroidMatch && oldAndroidMatch.length > 1) {
          if (parseFloat(oldAndroidMatch[1]) < 4.4) {
            isOldAndroid = true;
          }
        }
      }
      return !isOldAndroid && WebSocketImpl !== null && !WebSocketConnection.forceDisallow_;
    }
    /**
     * Returns true if we previously failed to connect with this transport.
     */
    static previouslyFailed() {
      return PersistentStorage.isInMemoryStorage || PersistentStorage.get("previous_websocket_failure") === true;
    }
    markConnectionHealthy() {
      PersistentStorage.remove("previous_websocket_failure");
    }
    appendFrame_(data) {
      this.frames.push(data);
      if (this.frames.length === this.totalFrames) {
        const fullMess = this.frames.join("");
        this.frames = null;
        const jsonMess = jsonEval(fullMess);
        this.onMessage(jsonMess);
      }
    }
    /**
     * @param frameCount - The number of frames we are expecting from the server
     */
    handleNewFrameCount_(frameCount) {
      this.totalFrames = frameCount;
      this.frames = [];
    }
    /**
     * Attempts to parse a frame count out of some text. If it can't, assumes a value of 1
     * @returns Any remaining data to be process, or null if there is none
     */
    extractFrameCount_(data) {
      assert(this.frames === null, "We already have a frame buffer");
      if (data.length <= 6) {
        const frameCount = Number(data);
        if (!isNaN(frameCount)) {
          this.handleNewFrameCount_(frameCount);
          return null;
        }
      }
      this.handleNewFrameCount_(1);
      return data;
    }
    /**
     * Process a websocket frame that has arrived from the server.
     * @param mess - The frame data
     */
    handleIncomingFrame(mess) {
      if (this.mySock === null) {
        return;
      }
      const data = mess["data"];
      this.bytesReceived += data.length;
      this.stats_.incrementCounter("bytes_received", data.length);
      this.resetKeepAlive();
      if (this.frames !== null) {
        this.appendFrame_(data);
      } else {
        const remainingData = this.extractFrameCount_(data);
        if (remainingData !== null) {
          this.appendFrame_(remainingData);
        }
      }
    }
    /**
     * Send a message to the server
     * @param data - The JSON object to transmit
     */
    send(data) {
      this.resetKeepAlive();
      const dataStr = stringify(data);
      this.bytesSent += dataStr.length;
      this.stats_.incrementCounter("bytes_sent", dataStr.length);
      const dataSegs = splitStringBySize(dataStr, WEBSOCKET_MAX_FRAME_SIZE);
      if (dataSegs.length > 1) {
        this.sendString_(String(dataSegs.length));
      }
      for (let i2 = 0; i2 < dataSegs.length; i2++) {
        this.sendString_(dataSegs[i2]);
      }
    }
    shutdown_() {
      this.isClosed_ = true;
      if (this.keepaliveTimer) {
        clearInterval(this.keepaliveTimer);
        this.keepaliveTimer = null;
      }
      if (this.mySock) {
        this.mySock.close();
        this.mySock = null;
      }
    }
    onClosed_() {
      if (!this.isClosed_) {
        this.log_("WebSocket is closing itself");
        this.shutdown_();
        if (this.onDisconnect) {
          this.onDisconnect(this.everConnected_);
          this.onDisconnect = null;
        }
      }
    }
    /**
     * External-facing close handler.
     * Close the websocket and kill the connection.
     */
    close() {
      if (!this.isClosed_) {
        this.log_("WebSocket is being closed");
        this.shutdown_();
      }
    }
    /**
     * Kill the current keepalive timer and start a new one, to ensure that it always fires N seconds after
     * the last activity.
     */
    resetKeepAlive() {
      clearInterval(this.keepaliveTimer);
      this.keepaliveTimer = setInterval(() => {
        if (this.mySock) {
          this.sendString_("0");
        }
        this.resetKeepAlive();
      }, Math.floor(WEBSOCKET_KEEPALIVE_INTERVAL));
    }
    /**
     * Send a string over the websocket.
     *
     * @param str - String to send.
     */
    sendString_(str) {
      try {
        this.mySock.send(str);
      } catch (e2) {
        this.log_("Exception thrown from WebSocket.send():", e2.message || e2.data, "Closing connection.");
        setTimeout(this.onClosed_.bind(this), 0);
      }
    }
  }
  WebSocketConnection.responsesRequiredToBeHealthy = 2;
  WebSocketConnection.healthyTimeout = 3e4;
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class TransportManager {
    /**
     * @param repoInfo - Metadata around the namespace we're connecting to
     */
    constructor(repoInfo) {
      this.initTransports_(repoInfo);
    }
    static get ALL_TRANSPORTS() {
      return [BrowserPollConnection, WebSocketConnection];
    }
    /**
     * Returns whether transport has been selected to ensure WebSocketConnection or BrowserPollConnection are not called after
     * TransportManager has already set up transports_
     */
    static get IS_TRANSPORT_INITIALIZED() {
      return this.globalTransportInitialized_;
    }
    initTransports_(repoInfo) {
      const isWebSocketsAvailable = WebSocketConnection && WebSocketConnection["isAvailable"]();
      let isSkipPollConnection = isWebSocketsAvailable && !WebSocketConnection.previouslyFailed();
      if (repoInfo.webSocketOnly) {
        if (!isWebSocketsAvailable) {
          warn("wss:// URL used, but browser isn't known to support websockets.  Trying anyway.");
        }
        isSkipPollConnection = true;
      }
      if (isSkipPollConnection) {
        this.transports_ = [WebSocketConnection];
      } else {
        const transports = this.transports_ = [];
        for (const transport of TransportManager.ALL_TRANSPORTS) {
          if (transport && transport["isAvailable"]()) {
            transports.push(transport);
          }
        }
        TransportManager.globalTransportInitialized_ = true;
      }
    }
    /**
     * @returns The constructor for the initial transport to use
     */
    initialTransport() {
      if (this.transports_.length > 0) {
        return this.transports_[0];
      } else {
        throw new Error("No transports available");
      }
    }
    /**
     * @returns The constructor for the next transport, or null
     */
    upgradeTransport() {
      if (this.transports_.length > 1) {
        return this.transports_[1];
      } else {
        return null;
      }
    }
  }
  TransportManager.globalTransportInitialized_ = false;
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const UPGRADE_TIMEOUT = 6e4;
  const DELAY_BEFORE_SENDING_EXTRA_REQUESTS = 5e3;
  const BYTES_SENT_HEALTHY_OVERRIDE = 10 * 1024;
  const BYTES_RECEIVED_HEALTHY_OVERRIDE = 100 * 1024;
  const MESSAGE_TYPE = "t";
  const MESSAGE_DATA = "d";
  const CONTROL_SHUTDOWN = "s";
  const CONTROL_RESET = "r";
  const CONTROL_ERROR = "e";
  const CONTROL_PONG = "o";
  const SWITCH_ACK = "a";
  const END_TRANSMISSION = "n";
  const PING = "p";
  const SERVER_HELLO = "h";
  class Connection {
    /**
     * @param id - an id for this connection
     * @param repoInfo_ - the info for the endpoint to connect to
     * @param applicationId_ - the Firebase App ID for this project
     * @param appCheckToken_ - The App Check Token for this device.
     * @param authToken_ - The auth token for this session.
     * @param onMessage_ - the callback to be triggered when a server-push message arrives
     * @param onReady_ - the callback to be triggered when this connection is ready to send messages.
     * @param onDisconnect_ - the callback to be triggered when a connection was lost
     * @param onKill_ - the callback to be triggered when this connection has permanently shut down.
     * @param lastSessionId - last session id in persistent connection. is used to clean up old session in real-time server
     */
    constructor(id, repoInfo_, applicationId_, appCheckToken_, authToken_, onMessage_, onReady_, onDisconnect_, onKill_, lastSessionId) {
      this.id = id;
      this.repoInfo_ = repoInfo_;
      this.applicationId_ = applicationId_;
      this.appCheckToken_ = appCheckToken_;
      this.authToken_ = authToken_;
      this.onMessage_ = onMessage_;
      this.onReady_ = onReady_;
      this.onDisconnect_ = onDisconnect_;
      this.onKill_ = onKill_;
      this.lastSessionId = lastSessionId;
      this.connectionCount = 0;
      this.pendingDataMessages = [];
      this.state_ = 0;
      this.log_ = logWrapper("c:" + this.id + ":");
      this.transportManager_ = new TransportManager(repoInfo_);
      this.log_("Connection created");
      this.start_();
    }
    /**
     * Starts a connection attempt
     */
    start_() {
      const conn = this.transportManager_.initialTransport();
      this.conn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, null, this.lastSessionId);
      this.primaryResponsesRequired_ = conn["responsesRequiredToBeHealthy"] || 0;
      const onMessageReceived = this.connReceiver_(this.conn_);
      const onConnectionLost = this.disconnReceiver_(this.conn_);
      this.tx_ = this.conn_;
      this.rx_ = this.conn_;
      this.secondaryConn_ = null;
      this.isHealthy_ = false;
      setTimeout(() => {
        this.conn_ && this.conn_.open(onMessageReceived, onConnectionLost);
      }, Math.floor(0));
      const healthyTimeoutMS = conn["healthyTimeout"] || 0;
      if (healthyTimeoutMS > 0) {
        this.healthyTimeout_ = setTimeoutNonBlocking(() => {
          this.healthyTimeout_ = null;
          if (!this.isHealthy_) {
            if (this.conn_ && this.conn_.bytesReceived > BYTES_RECEIVED_HEALTHY_OVERRIDE) {
              this.log_("Connection exceeded healthy timeout but has received " + this.conn_.bytesReceived + " bytes.  Marking connection healthy.");
              this.isHealthy_ = true;
              this.conn_.markConnectionHealthy();
            } else if (this.conn_ && this.conn_.bytesSent > BYTES_SENT_HEALTHY_OVERRIDE) {
              this.log_("Connection exceeded healthy timeout but has sent " + this.conn_.bytesSent + " bytes.  Leaving connection alive.");
            } else {
              this.log_("Closing unhealthy connection after timeout.");
              this.close();
            }
          }
        }, Math.floor(healthyTimeoutMS));
      }
    }
    nextTransportId_() {
      return "c:" + this.id + ":" + this.connectionCount++;
    }
    disconnReceiver_(conn) {
      return (everConnected) => {
        if (conn === this.conn_) {
          this.onConnectionLost_(everConnected);
        } else if (conn === this.secondaryConn_) {
          this.log_("Secondary connection lost.");
          this.onSecondaryConnectionLost_();
        } else {
          this.log_("closing an old connection");
        }
      };
    }
    connReceiver_(conn) {
      return (message) => {
        if (this.state_ !== 2) {
          if (conn === this.rx_) {
            this.onPrimaryMessageReceived_(message);
          } else if (conn === this.secondaryConn_) {
            this.onSecondaryMessageReceived_(message);
          } else {
            this.log_("message on old connection");
          }
        }
      };
    }
    /**
     * @param dataMsg - An arbitrary data message to be sent to the server
     */
    sendRequest(dataMsg) {
      const msg = { t: "d", d: dataMsg };
      this.sendData_(msg);
    }
    tryCleanupConnection() {
      if (this.tx_ === this.secondaryConn_ && this.rx_ === this.secondaryConn_) {
        this.log_("cleaning up and promoting a connection: " + this.secondaryConn_.connId);
        this.conn_ = this.secondaryConn_;
        this.secondaryConn_ = null;
      }
    }
    onSecondaryControl_(controlData) {
      if (MESSAGE_TYPE in controlData) {
        const cmd = controlData[MESSAGE_TYPE];
        if (cmd === SWITCH_ACK) {
          this.upgradeIfSecondaryHealthy_();
        } else if (cmd === CONTROL_RESET) {
          this.log_("Got a reset on secondary, closing it");
          this.secondaryConn_.close();
          if (this.tx_ === this.secondaryConn_ || this.rx_ === this.secondaryConn_) {
            this.close();
          }
        } else if (cmd === CONTROL_PONG) {
          this.log_("got pong on secondary.");
          this.secondaryResponsesRequired_--;
          this.upgradeIfSecondaryHealthy_();
        }
      }
    }
    onSecondaryMessageReceived_(parsedData) {
      const layer = requireKey("t", parsedData);
      const data = requireKey("d", parsedData);
      if (layer === "c") {
        this.onSecondaryControl_(data);
      } else if (layer === "d") {
        this.pendingDataMessages.push(data);
      } else {
        throw new Error("Unknown protocol layer: " + layer);
      }
    }
    upgradeIfSecondaryHealthy_() {
      if (this.secondaryResponsesRequired_ <= 0) {
        this.log_("Secondary connection is healthy.");
        this.isHealthy_ = true;
        this.secondaryConn_.markConnectionHealthy();
        this.proceedWithUpgrade_();
      } else {
        this.log_("sending ping on secondary.");
        this.secondaryConn_.send({ t: "c", d: { t: PING, d: {} } });
      }
    }
    proceedWithUpgrade_() {
      this.secondaryConn_.start();
      this.log_("sending client ack on secondary");
      this.secondaryConn_.send({ t: "c", d: { t: SWITCH_ACK, d: {} } });
      this.log_("Ending transmission on primary");
      this.conn_.send({ t: "c", d: { t: END_TRANSMISSION, d: {} } });
      this.tx_ = this.secondaryConn_;
      this.tryCleanupConnection();
    }
    onPrimaryMessageReceived_(parsedData) {
      const layer = requireKey("t", parsedData);
      const data = requireKey("d", parsedData);
      if (layer === "c") {
        this.onControl_(data);
      } else if (layer === "d") {
        this.onDataMessage_(data);
      }
    }
    onDataMessage_(message) {
      this.onPrimaryResponse_();
      this.onMessage_(message);
    }
    onPrimaryResponse_() {
      if (!this.isHealthy_) {
        this.primaryResponsesRequired_--;
        if (this.primaryResponsesRequired_ <= 0) {
          this.log_("Primary connection is healthy.");
          this.isHealthy_ = true;
          this.conn_.markConnectionHealthy();
        }
      }
    }
    onControl_(controlData) {
      const cmd = requireKey(MESSAGE_TYPE, controlData);
      if (MESSAGE_DATA in controlData) {
        const payload = controlData[MESSAGE_DATA];
        if (cmd === SERVER_HELLO) {
          const handshakePayload = Object.assign({}, payload);
          if (this.repoInfo_.isUsingEmulator) {
            handshakePayload.h = this.repoInfo_.host;
          }
          this.onHandshake_(handshakePayload);
        } else if (cmd === END_TRANSMISSION) {
          this.log_("recvd end transmission on primary");
          this.rx_ = this.secondaryConn_;
          for (let i2 = 0; i2 < this.pendingDataMessages.length; ++i2) {
            this.onDataMessage_(this.pendingDataMessages[i2]);
          }
          this.pendingDataMessages = [];
          this.tryCleanupConnection();
        } else if (cmd === CONTROL_SHUTDOWN) {
          this.onConnectionShutdown_(payload);
        } else if (cmd === CONTROL_RESET) {
          this.onReset_(payload);
        } else if (cmd === CONTROL_ERROR) {
          error("Server Error: " + payload);
        } else if (cmd === CONTROL_PONG) {
          this.log_("got pong on primary.");
          this.onPrimaryResponse_();
          this.sendPingOnPrimaryIfNecessary_();
        } else {
          error("Unknown control packet command: " + cmd);
        }
      }
    }
    /**
     * @param handshake - The handshake data returned from the server
     */
    onHandshake_(handshake) {
      const timestamp = handshake.ts;
      const version2 = handshake.v;
      const host = handshake.h;
      this.sessionId = handshake.s;
      this.repoInfo_.host = host;
      if (this.state_ === 0) {
        this.conn_.start();
        this.onConnectionEstablished_(this.conn_, timestamp);
        if (PROTOCOL_VERSION !== version2) {
          warn("Protocol version mismatch detected");
        }
        this.tryStartUpgrade_();
      }
    }
    tryStartUpgrade_() {
      const conn = this.transportManager_.upgradeTransport();
      if (conn) {
        this.startUpgrade_(conn);
      }
    }
    startUpgrade_(conn) {
      this.secondaryConn_ = new conn(this.nextTransportId_(), this.repoInfo_, this.applicationId_, this.appCheckToken_, this.authToken_, this.sessionId);
      this.secondaryResponsesRequired_ = conn["responsesRequiredToBeHealthy"] || 0;
      const onMessage = this.connReceiver_(this.secondaryConn_);
      const onDisconnect = this.disconnReceiver_(this.secondaryConn_);
      this.secondaryConn_.open(onMessage, onDisconnect);
      setTimeoutNonBlocking(() => {
        if (this.secondaryConn_) {
          this.log_("Timed out trying to upgrade.");
          this.secondaryConn_.close();
        }
      }, Math.floor(UPGRADE_TIMEOUT));
    }
    onReset_(host) {
      this.log_("Reset packet received.  New host: " + host);
      this.repoInfo_.host = host;
      if (this.state_ === 1) {
        this.close();
      } else {
        this.closeConnections_();
        this.start_();
      }
    }
    onConnectionEstablished_(conn, timestamp) {
      this.log_("Realtime connection established.");
      this.conn_ = conn;
      this.state_ = 1;
      if (this.onReady_) {
        this.onReady_(timestamp, this.sessionId);
        this.onReady_ = null;
      }
      if (this.primaryResponsesRequired_ === 0) {
        this.log_("Primary connection is healthy.");
        this.isHealthy_ = true;
      } else {
        setTimeoutNonBlocking(() => {
          this.sendPingOnPrimaryIfNecessary_();
        }, Math.floor(DELAY_BEFORE_SENDING_EXTRA_REQUESTS));
      }
    }
    sendPingOnPrimaryIfNecessary_() {
      if (!this.isHealthy_ && this.state_ === 1) {
        this.log_("sending ping on primary.");
        this.sendData_({ t: "c", d: { t: PING, d: {} } });
      }
    }
    onSecondaryConnectionLost_() {
      const conn = this.secondaryConn_;
      this.secondaryConn_ = null;
      if (this.tx_ === conn || this.rx_ === conn) {
        this.close();
      }
    }
    /**
     * @param everConnected - Whether or not the connection ever reached a server. Used to determine if
     * we should flush the host cache
     */
    onConnectionLost_(everConnected) {
      this.conn_ = null;
      if (!everConnected && this.state_ === 0) {
        this.log_("Realtime connection failed.");
        if (this.repoInfo_.isCacheableHost()) {
          PersistentStorage.remove("host:" + this.repoInfo_.host);
          this.repoInfo_.internalHost = this.repoInfo_.host;
        }
      } else if (this.state_ === 1) {
        this.log_("Realtime connection lost.");
      }
      this.close();
    }
    onConnectionShutdown_(reason) {
      this.log_("Connection shutdown command received. Shutting down...");
      if (this.onKill_) {
        this.onKill_(reason);
        this.onKill_ = null;
      }
      this.onDisconnect_ = null;
      this.close();
    }
    sendData_(data) {
      if (this.state_ !== 1) {
        throw "Connection is not connected";
      } else {
        this.tx_.send(data);
      }
    }
    /**
     * Cleans up this connection, calling the appropriate callbacks
     */
    close() {
      if (this.state_ !== 2) {
        this.log_("Closing realtime connection.");
        this.state_ = 2;
        this.closeConnections_();
        if (this.onDisconnect_) {
          this.onDisconnect_();
          this.onDisconnect_ = null;
        }
      }
    }
    closeConnections_() {
      this.log_("Shutting down all connections");
      if (this.conn_) {
        this.conn_.close();
        this.conn_ = null;
      }
      if (this.secondaryConn_) {
        this.secondaryConn_.close();
        this.secondaryConn_ = null;
      }
      if (this.healthyTimeout_) {
        clearTimeout(this.healthyTimeout_);
        this.healthyTimeout_ = null;
      }
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class ServerActions {
    put(pathString, data, onComplete, hash) {
    }
    merge(pathString, data, onComplete, hash) {
    }
    /**
     * Refreshes the auth token for the current connection.
     * @param token - The authentication token
     */
    refreshAuthToken(token) {
    }
    /**
     * Refreshes the app check token for the current connection.
     * @param token The app check token
     */
    refreshAppCheckToken(token) {
    }
    onDisconnectPut(pathString, data, onComplete) {
    }
    onDisconnectMerge(pathString, data, onComplete) {
    }
    onDisconnectCancel(pathString, onComplete) {
    }
    reportStats(stats) {
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class EventEmitter2 {
    constructor(allowedEvents_) {
      this.allowedEvents_ = allowedEvents_;
      this.listeners_ = {};
      assert(Array.isArray(allowedEvents_) && allowedEvents_.length > 0, "Requires a non-empty array");
    }
    /**
     * To be called by derived classes to trigger events.
     */
    trigger(eventType, ...varArgs) {
      if (Array.isArray(this.listeners_[eventType])) {
        const listeners = [...this.listeners_[eventType]];
        for (let i2 = 0; i2 < listeners.length; i2++) {
          listeners[i2].callback.apply(listeners[i2].context, varArgs);
        }
      }
    }
    on(eventType, callback, context) {
      this.validateEventType_(eventType);
      this.listeners_[eventType] = this.listeners_[eventType] || [];
      this.listeners_[eventType].push({ callback, context });
      const eventData = this.getInitialEvent(eventType);
      if (eventData) {
        callback.apply(context, eventData);
      }
    }
    off(eventType, callback, context) {
      this.validateEventType_(eventType);
      const listeners = this.listeners_[eventType] || [];
      for (let i2 = 0; i2 < listeners.length; i2++) {
        if (listeners[i2].callback === callback && (!context || context === listeners[i2].context)) {
          listeners.splice(i2, 1);
          return;
        }
      }
    }
    validateEventType_(eventType) {
      assert(this.allowedEvents_.find((et) => {
        return et === eventType;
      }), "Unknown event: " + eventType);
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class OnlineMonitor extends EventEmitter2 {
    constructor() {
      super(["online"]);
      this.online_ = true;
      if (typeof window !== "undefined" && typeof window.addEventListener !== "undefined" && !isMobileCordova()) {
        window.addEventListener("online", () => {
          if (!this.online_) {
            this.online_ = true;
            this.trigger("online", true);
          }
        }, false);
        window.addEventListener("offline", () => {
          if (this.online_) {
            this.online_ = false;
            this.trigger("online", false);
          }
        }, false);
      }
    }
    static getInstance() {
      return new OnlineMonitor();
    }
    getInitialEvent(eventType) {
      assert(eventType === "online", "Unknown event type: " + eventType);
      return [this.online_];
    }
    currentlyOnline() {
      return this.online_;
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const MAX_PATH_DEPTH = 32;
  const MAX_PATH_LENGTH_BYTES = 768;
  class Path {
    /**
     * @param pathOrString - Path string to parse, or another path, or the raw
     * tokens array
     */
    constructor(pathOrString, pieceNum) {
      if (pieceNum === void 0) {
        this.pieces_ = pathOrString.split("/");
        let copyTo = 0;
        for (let i2 = 0; i2 < this.pieces_.length; i2++) {
          if (this.pieces_[i2].length > 0) {
            this.pieces_[copyTo] = this.pieces_[i2];
            copyTo++;
          }
        }
        this.pieces_.length = copyTo;
        this.pieceNum_ = 0;
      } else {
        this.pieces_ = pathOrString;
        this.pieceNum_ = pieceNum;
      }
    }
    toString() {
      let pathString = "";
      for (let i2 = this.pieceNum_; i2 < this.pieces_.length; i2++) {
        if (this.pieces_[i2] !== "") {
          pathString += "/" + this.pieces_[i2];
        }
      }
      return pathString || "/";
    }
  }
  function newEmptyPath() {
    return new Path("");
  }
  function pathGetFront(path) {
    if (path.pieceNum_ >= path.pieces_.length) {
      return null;
    }
    return path.pieces_[path.pieceNum_];
  }
  function pathGetLength(path) {
    return path.pieces_.length - path.pieceNum_;
  }
  function pathPopFront(path) {
    let pieceNum = path.pieceNum_;
    if (pieceNum < path.pieces_.length) {
      pieceNum++;
    }
    return new Path(path.pieces_, pieceNum);
  }
  function pathGetBack(path) {
    if (path.pieceNum_ < path.pieces_.length) {
      return path.pieces_[path.pieces_.length - 1];
    }
    return null;
  }
  function pathToUrlEncodedString(path) {
    let pathString = "";
    for (let i2 = path.pieceNum_; i2 < path.pieces_.length; i2++) {
      if (path.pieces_[i2] !== "") {
        pathString += "/" + encodeURIComponent(String(path.pieces_[i2]));
      }
    }
    return pathString || "/";
  }
  function pathSlice(path, begin = 0) {
    return path.pieces_.slice(path.pieceNum_ + begin);
  }
  function pathParent(path) {
    if (path.pieceNum_ >= path.pieces_.length) {
      return null;
    }
    const pieces = [];
    for (let i2 = path.pieceNum_; i2 < path.pieces_.length - 1; i2++) {
      pieces.push(path.pieces_[i2]);
    }
    return new Path(pieces, 0);
  }
  function pathChild(path, childPathObj) {
    const pieces = [];
    for (let i2 = path.pieceNum_; i2 < path.pieces_.length; i2++) {
      pieces.push(path.pieces_[i2]);
    }
    if (childPathObj instanceof Path) {
      for (let i2 = childPathObj.pieceNum_; i2 < childPathObj.pieces_.length; i2++) {
        pieces.push(childPathObj.pieces_[i2]);
      }
    } else {
      const childPieces = childPathObj.split("/");
      for (let i2 = 0; i2 < childPieces.length; i2++) {
        if (childPieces[i2].length > 0) {
          pieces.push(childPieces[i2]);
        }
      }
    }
    return new Path(pieces, 0);
  }
  function pathIsEmpty(path) {
    return path.pieceNum_ >= path.pieces_.length;
  }
  function newRelativePath(outerPath, innerPath) {
    const outer = pathGetFront(outerPath), inner = pathGetFront(innerPath);
    if (outer === null) {
      return innerPath;
    } else if (outer === inner) {
      return newRelativePath(pathPopFront(outerPath), pathPopFront(innerPath));
    } else {
      throw new Error("INTERNAL ERROR: innerPath (" + innerPath + ") is not within outerPath (" + outerPath + ")");
    }
  }
  function pathEquals(path, other) {
    if (pathGetLength(path) !== pathGetLength(other)) {
      return false;
    }
    for (let i2 = path.pieceNum_, j2 = other.pieceNum_; i2 <= path.pieces_.length; i2++, j2++) {
      if (path.pieces_[i2] !== other.pieces_[j2]) {
        return false;
      }
    }
    return true;
  }
  function pathContains(path, other) {
    let i2 = path.pieceNum_;
    let j2 = other.pieceNum_;
    if (pathGetLength(path) > pathGetLength(other)) {
      return false;
    }
    while (i2 < path.pieces_.length) {
      if (path.pieces_[i2] !== other.pieces_[j2]) {
        return false;
      }
      ++i2;
      ++j2;
    }
    return true;
  }
  class ValidationPath {
    /**
     * @param path - Initial Path.
     * @param errorPrefix_ - Prefix for any error messages.
     */
    constructor(path, errorPrefix_) {
      this.errorPrefix_ = errorPrefix_;
      this.parts_ = pathSlice(path, 0);
      this.byteLength_ = Math.max(1, this.parts_.length);
      for (let i2 = 0; i2 < this.parts_.length; i2++) {
        this.byteLength_ += stringLength(this.parts_[i2]);
      }
      validationPathCheckValid(this);
    }
  }
  function validationPathPush(validationPath, child2) {
    if (validationPath.parts_.length > 0) {
      validationPath.byteLength_ += 1;
    }
    validationPath.parts_.push(child2);
    validationPath.byteLength_ += stringLength(child2);
    validationPathCheckValid(validationPath);
  }
  function validationPathPop(validationPath) {
    const last = validationPath.parts_.pop();
    validationPath.byteLength_ -= stringLength(last);
    if (validationPath.parts_.length > 0) {
      validationPath.byteLength_ -= 1;
    }
  }
  function validationPathCheckValid(validationPath) {
    if (validationPath.byteLength_ > MAX_PATH_LENGTH_BYTES) {
      throw new Error(validationPath.errorPrefix_ + "has a key path longer than " + MAX_PATH_LENGTH_BYTES + " bytes (" + validationPath.byteLength_ + ").");
    }
    if (validationPath.parts_.length > MAX_PATH_DEPTH) {
      throw new Error(validationPath.errorPrefix_ + "path specified exceeds the maximum depth that can be written (" + MAX_PATH_DEPTH + ") or object contains a cycle " + validationPathToErrorString(validationPath));
    }
  }
  function validationPathToErrorString(validationPath) {
    if (validationPath.parts_.length === 0) {
      return "";
    }
    return "in property '" + validationPath.parts_.join(".") + "'";
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class VisibilityMonitor extends EventEmitter2 {
    constructor() {
      super(["visible"]);
      let hidden;
      let visibilityChange;
      if (typeof document !== "undefined" && typeof document.addEventListener !== "undefined") {
        if (typeof document["hidden"] !== "undefined") {
          visibilityChange = "visibilitychange";
          hidden = "hidden";
        } else if (typeof document["mozHidden"] !== "undefined") {
          visibilityChange = "mozvisibilitychange";
          hidden = "mozHidden";
        } else if (typeof document["msHidden"] !== "undefined") {
          visibilityChange = "msvisibilitychange";
          hidden = "msHidden";
        } else if (typeof document["webkitHidden"] !== "undefined") {
          visibilityChange = "webkitvisibilitychange";
          hidden = "webkitHidden";
        }
      }
      this.visible_ = true;
      if (visibilityChange) {
        document.addEventListener(visibilityChange, () => {
          const visible = !document[hidden];
          if (visible !== this.visible_) {
            this.visible_ = visible;
            this.trigger("visible", visible);
          }
        }, false);
      }
    }
    static getInstance() {
      return new VisibilityMonitor();
    }
    getInitialEvent(eventType) {
      assert(eventType === "visible", "Unknown event type: " + eventType);
      return [this.visible_];
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const RECONNECT_MIN_DELAY = 1e3;
  const RECONNECT_MAX_DELAY_DEFAULT = 60 * 5 * 1e3;
  const RECONNECT_MAX_DELAY_FOR_ADMINS = 30 * 1e3;
  const RECONNECT_DELAY_MULTIPLIER = 1.3;
  const RECONNECT_DELAY_RESET_TIMEOUT = 3e4;
  const SERVER_KILL_INTERRUPT_REASON = "server_kill";
  const INVALID_TOKEN_THRESHOLD = 3;
  class PersistentConnection extends ServerActions {
    /**
     * @param repoInfo_ - Data about the namespace we are connecting to
     * @param applicationId_ - The Firebase App ID for this project
     * @param onDataUpdate_ - A callback for new data from the server
     */
    constructor(repoInfo_, applicationId_, onDataUpdate_, onConnectStatus_, onServerInfoUpdate_, authTokenProvider_, appCheckTokenProvider_, authOverride_) {
      super();
      this.repoInfo_ = repoInfo_;
      this.applicationId_ = applicationId_;
      this.onDataUpdate_ = onDataUpdate_;
      this.onConnectStatus_ = onConnectStatus_;
      this.onServerInfoUpdate_ = onServerInfoUpdate_;
      this.authTokenProvider_ = authTokenProvider_;
      this.appCheckTokenProvider_ = appCheckTokenProvider_;
      this.authOverride_ = authOverride_;
      this.id = PersistentConnection.nextPersistentConnectionId_++;
      this.log_ = logWrapper("p:" + this.id + ":");
      this.interruptReasons_ = {};
      this.listens = /* @__PURE__ */ new Map();
      this.outstandingPuts_ = [];
      this.outstandingGets_ = [];
      this.outstandingPutCount_ = 0;
      this.outstandingGetCount_ = 0;
      this.onDisconnectRequestQueue_ = [];
      this.connected_ = false;
      this.reconnectDelay_ = RECONNECT_MIN_DELAY;
      this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_DEFAULT;
      this.securityDebugCallback_ = null;
      this.lastSessionId = null;
      this.establishConnectionTimer_ = null;
      this.visible_ = false;
      this.requestCBHash_ = {};
      this.requestNumber_ = 0;
      this.realtime_ = null;
      this.authToken_ = null;
      this.appCheckToken_ = null;
      this.forceTokenRefresh_ = false;
      this.invalidAuthTokenCount_ = 0;
      this.invalidAppCheckTokenCount_ = 0;
      this.firstConnection_ = true;
      this.lastConnectionAttemptTime_ = null;
      this.lastConnectionEstablishedTime_ = null;
      if (authOverride_ && !isNodeSdk()) {
        throw new Error("Auth override specified in options, but not supported on non Node.js platforms");
      }
      VisibilityMonitor.getInstance().on("visible", this.onVisible_, this);
      if (repoInfo_.host.indexOf("fblocal") === -1) {
        OnlineMonitor.getInstance().on("online", this.onOnline_, this);
      }
    }
    sendRequest(action, body, onResponse) {
      const curReqNum = ++this.requestNumber_;
      const msg = { r: curReqNum, a: action, b: body };
      this.log_(stringify(msg));
      assert(this.connected_, "sendRequest call when we're not connected not allowed.");
      this.realtime_.sendRequest(msg);
      if (onResponse) {
        this.requestCBHash_[curReqNum] = onResponse;
      }
    }
    get(query) {
      this.initConnection_();
      const deferred = new Deferred();
      const request = {
        p: query._path.toString(),
        q: query._queryObject
      };
      const outstandingGet = {
        action: "g",
        request,
        onComplete: (message) => {
          const payload = message["d"];
          if (message["s"] === "ok") {
            deferred.resolve(payload);
          } else {
            deferred.reject(payload);
          }
        }
      };
      this.outstandingGets_.push(outstandingGet);
      this.outstandingGetCount_++;
      const index2 = this.outstandingGets_.length - 1;
      if (this.connected_) {
        this.sendGet_(index2);
      }
      return deferred.promise;
    }
    listen(query, currentHashFn, tag, onComplete) {
      this.initConnection_();
      const queryId = query._queryIdentifier;
      const pathString = query._path.toString();
      this.log_("Listen called for " + pathString + " " + queryId);
      if (!this.listens.has(pathString)) {
        this.listens.set(pathString, /* @__PURE__ */ new Map());
      }
      assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), "listen() called for non-default but complete query");
      assert(!this.listens.get(pathString).has(queryId), `listen() called twice for same path/queryId.`);
      const listenSpec = {
        onComplete,
        hashFn: currentHashFn,
        query,
        tag
      };
      this.listens.get(pathString).set(queryId, listenSpec);
      if (this.connected_) {
        this.sendListen_(listenSpec);
      }
    }
    sendGet_(index2) {
      const get2 = this.outstandingGets_[index2];
      this.sendRequest("g", get2.request, (message) => {
        delete this.outstandingGets_[index2];
        this.outstandingGetCount_--;
        if (this.outstandingGetCount_ === 0) {
          this.outstandingGets_ = [];
        }
        if (get2.onComplete) {
          get2.onComplete(message);
        }
      });
    }
    sendListen_(listenSpec) {
      const query = listenSpec.query;
      const pathString = query._path.toString();
      const queryId = query._queryIdentifier;
      this.log_("Listen on " + pathString + " for " + queryId);
      const req = {
        /*path*/
        p: pathString
      };
      const action = "q";
      if (listenSpec.tag) {
        req["q"] = query._queryObject;
        req["t"] = listenSpec.tag;
      }
      req[
        /*hash*/
        "h"
      ] = listenSpec.hashFn();
      this.sendRequest(action, req, (message) => {
        const payload = message[
          /*data*/
          "d"
        ];
        const status = message[
          /*status*/
          "s"
        ];
        PersistentConnection.warnOnListenWarnings_(payload, query);
        const currentListenSpec = this.listens.get(pathString) && this.listens.get(pathString).get(queryId);
        if (currentListenSpec === listenSpec) {
          this.log_("listen response", message);
          if (status !== "ok") {
            this.removeListen_(pathString, queryId);
          }
          if (listenSpec.onComplete) {
            listenSpec.onComplete(status, payload);
          }
        }
      });
    }
    static warnOnListenWarnings_(payload, query) {
      if (payload && typeof payload === "object" && contains(payload, "w")) {
        const warnings = safeGet(payload, "w");
        if (Array.isArray(warnings) && ~warnings.indexOf("no_index")) {
          const indexSpec = '".indexOn": "' + query._queryParams.getIndex().toString() + '"';
          const indexPath = query._path.toString();
          warn(`Using an unspecified index. Your data will be downloaded and filtered on the client. Consider adding ${indexSpec} at ${indexPath} to your security rules for better performance.`);
        }
      }
    }
    refreshAuthToken(token) {
      this.authToken_ = token;
      this.log_("Auth token refreshed");
      if (this.authToken_) {
        this.tryAuth();
      } else {
        if (this.connected_) {
          this.sendRequest("unauth", {}, () => {
          });
        }
      }
      this.reduceReconnectDelayIfAdminCredential_(token);
    }
    reduceReconnectDelayIfAdminCredential_(credential) {
      const isFirebaseSecret = credential && credential.length === 40;
      if (isFirebaseSecret || isAdmin(credential)) {
        this.log_("Admin auth credential detected.  Reducing max reconnect time.");
        this.maxReconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
      }
    }
    refreshAppCheckToken(token) {
      this.appCheckToken_ = token;
      this.log_("App check token refreshed");
      if (this.appCheckToken_) {
        this.tryAppCheck();
      } else {
        if (this.connected_) {
          this.sendRequest("unappeck", {}, () => {
          });
        }
      }
    }
    /**
     * Attempts to authenticate with the given credentials. If the authentication attempt fails, it's triggered like
     * a auth revoked (the connection is closed).
     */
    tryAuth() {
      if (this.connected_ && this.authToken_) {
        const token = this.authToken_;
        const authMethod = isValidFormat(token) ? "auth" : "gauth";
        const requestData = { cred: token };
        if (this.authOverride_ === null) {
          requestData["noauth"] = true;
        } else if (typeof this.authOverride_ === "object") {
          requestData["authvar"] = this.authOverride_;
        }
        this.sendRequest(authMethod, requestData, (res) => {
          const status = res[
            /*status*/
            "s"
          ];
          const data = res[
            /*data*/
            "d"
          ] || "error";
          if (this.authToken_ === token) {
            if (status === "ok") {
              this.invalidAuthTokenCount_ = 0;
            } else {
              this.onAuthRevoked_(status, data);
            }
          }
        });
      }
    }
    /**
     * Attempts to authenticate with the given token. If the authentication
     * attempt fails, it's triggered like the token was revoked (the connection is
     * closed).
     */
    tryAppCheck() {
      if (this.connected_ && this.appCheckToken_) {
        this.sendRequest("appcheck", { "token": this.appCheckToken_ }, (res) => {
          const status = res[
            /*status*/
            "s"
          ];
          const data = res[
            /*data*/
            "d"
          ] || "error";
          if (status === "ok") {
            this.invalidAppCheckTokenCount_ = 0;
          } else {
            this.onAppCheckRevoked_(status, data);
          }
        });
      }
    }
    /**
     * @inheritDoc
     */
    unlisten(query, tag) {
      const pathString = query._path.toString();
      const queryId = query._queryIdentifier;
      this.log_("Unlisten called for " + pathString + " " + queryId);
      assert(query._queryParams.isDefault() || !query._queryParams.loadsAllData(), "unlisten() called for non-default but complete query");
      const listen = this.removeListen_(pathString, queryId);
      if (listen && this.connected_) {
        this.sendUnlisten_(pathString, queryId, query._queryObject, tag);
      }
    }
    sendUnlisten_(pathString, queryId, queryObj, tag) {
      this.log_("Unlisten on " + pathString + " for " + queryId);
      const req = {
        /*path*/
        p: pathString
      };
      const action = "n";
      if (tag) {
        req["q"] = queryObj;
        req["t"] = tag;
      }
      this.sendRequest(action, req);
    }
    onDisconnectPut(pathString, data, onComplete) {
      this.initConnection_();
      if (this.connected_) {
        this.sendOnDisconnect_("o", pathString, data, onComplete);
      } else {
        this.onDisconnectRequestQueue_.push({
          pathString,
          action: "o",
          data,
          onComplete
        });
      }
    }
    onDisconnectMerge(pathString, data, onComplete) {
      this.initConnection_();
      if (this.connected_) {
        this.sendOnDisconnect_("om", pathString, data, onComplete);
      } else {
        this.onDisconnectRequestQueue_.push({
          pathString,
          action: "om",
          data,
          onComplete
        });
      }
    }
    onDisconnectCancel(pathString, onComplete) {
      this.initConnection_();
      if (this.connected_) {
        this.sendOnDisconnect_("oc", pathString, null, onComplete);
      } else {
        this.onDisconnectRequestQueue_.push({
          pathString,
          action: "oc",
          data: null,
          onComplete
        });
      }
    }
    sendOnDisconnect_(action, pathString, data, onComplete) {
      const request = {
        /*path*/
        p: pathString,
        /*data*/
        d: data
      };
      this.log_("onDisconnect " + action, request);
      this.sendRequest(action, request, (response) => {
        if (onComplete) {
          setTimeout(() => {
            onComplete(response[
              /*status*/
              "s"
            ], response[
              /* data */
              "d"
            ]);
          }, Math.floor(0));
        }
      });
    }
    put(pathString, data, onComplete, hash) {
      this.putInternal("p", pathString, data, onComplete, hash);
    }
    merge(pathString, data, onComplete, hash) {
      this.putInternal("m", pathString, data, onComplete, hash);
    }
    putInternal(action, pathString, data, onComplete, hash) {
      this.initConnection_();
      const request = {
        /*path*/
        p: pathString,
        /*data*/
        d: data
      };
      if (hash !== void 0) {
        request[
          /*hash*/
          "h"
        ] = hash;
      }
      this.outstandingPuts_.push({
        action,
        request,
        onComplete
      });
      this.outstandingPutCount_++;
      const index2 = this.outstandingPuts_.length - 1;
      if (this.connected_) {
        this.sendPut_(index2);
      } else {
        this.log_("Buffering put: " + pathString);
      }
    }
    sendPut_(index2) {
      const action = this.outstandingPuts_[index2].action;
      const request = this.outstandingPuts_[index2].request;
      const onComplete = this.outstandingPuts_[index2].onComplete;
      this.outstandingPuts_[index2].queued = this.connected_;
      this.sendRequest(action, request, (message) => {
        this.log_(action + " response", message);
        delete this.outstandingPuts_[index2];
        this.outstandingPutCount_--;
        if (this.outstandingPutCount_ === 0) {
          this.outstandingPuts_ = [];
        }
        if (onComplete) {
          onComplete(message[
            /*status*/
            "s"
          ], message[
            /* data */
            "d"
          ]);
        }
      });
    }
    reportStats(stats) {
      if (this.connected_) {
        const request = {
          /*counters*/
          c: stats
        };
        this.log_("reportStats", request);
        this.sendRequest(
          /*stats*/
          "s",
          request,
          (result) => {
            const status = result[
              /*status*/
              "s"
            ];
            if (status !== "ok") {
              const errorReason = result[
                /* data */
                "d"
              ];
              this.log_("reportStats", "Error sending stats: " + errorReason);
            }
          }
        );
      }
    }
    onDataMessage_(message) {
      if ("r" in message) {
        this.log_("from server: " + stringify(message));
        const reqNum = message["r"];
        const onResponse = this.requestCBHash_[reqNum];
        if (onResponse) {
          delete this.requestCBHash_[reqNum];
          onResponse(message[
            /*body*/
            "b"
          ]);
        }
      } else if ("error" in message) {
        throw "A server-side error has occurred: " + message["error"];
      } else if ("a" in message) {
        this.onDataPush_(message["a"], message["b"]);
      }
    }
    onDataPush_(action, body) {
      this.log_("handleServerMessage", action, body);
      if (action === "d") {
        this.onDataUpdate_(
          body[
            /*path*/
            "p"
          ],
          body[
            /*data*/
            "d"
          ],
          /*isMerge*/
          false,
          body["t"]
        );
      } else if (action === "m") {
        this.onDataUpdate_(
          body[
            /*path*/
            "p"
          ],
          body[
            /*data*/
            "d"
          ],
          /*isMerge=*/
          true,
          body["t"]
        );
      } else if (action === "c") {
        this.onListenRevoked_(body[
          /*path*/
          "p"
        ], body[
          /*query*/
          "q"
        ]);
      } else if (action === "ac") {
        this.onAuthRevoked_(body[
          /*status code*/
          "s"
        ], body[
          /* explanation */
          "d"
        ]);
      } else if (action === "apc") {
        this.onAppCheckRevoked_(body[
          /*status code*/
          "s"
        ], body[
          /* explanation */
          "d"
        ]);
      } else if (action === "sd") {
        this.onSecurityDebugPacket_(body);
      } else {
        error("Unrecognized action received from server: " + stringify(action) + "\nAre you using the latest client?");
      }
    }
    onReady_(timestamp, sessionId) {
      this.log_("connection ready");
      this.connected_ = true;
      this.lastConnectionEstablishedTime_ = (/* @__PURE__ */ new Date()).getTime();
      this.handleTimestamp_(timestamp);
      this.lastSessionId = sessionId;
      if (this.firstConnection_) {
        this.sendConnectStats_();
      }
      this.restoreState_();
      this.firstConnection_ = false;
      this.onConnectStatus_(true);
    }
    scheduleConnect_(timeout) {
      assert(!this.realtime_, "Scheduling a connect when we're already connected/ing?");
      if (this.establishConnectionTimer_) {
        clearTimeout(this.establishConnectionTimer_);
      }
      this.establishConnectionTimer_ = setTimeout(() => {
        this.establishConnectionTimer_ = null;
        this.establishConnection_();
      }, Math.floor(timeout));
    }
    initConnection_() {
      if (!this.realtime_ && this.firstConnection_) {
        this.scheduleConnect_(0);
      }
    }
    onVisible_(visible) {
      if (visible && !this.visible_ && this.reconnectDelay_ === this.maxReconnectDelay_) {
        this.log_("Window became visible.  Reducing delay.");
        this.reconnectDelay_ = RECONNECT_MIN_DELAY;
        if (!this.realtime_) {
          this.scheduleConnect_(0);
        }
      }
      this.visible_ = visible;
    }
    onOnline_(online) {
      if (online) {
        this.log_("Browser went online.");
        this.reconnectDelay_ = RECONNECT_MIN_DELAY;
        if (!this.realtime_) {
          this.scheduleConnect_(0);
        }
      } else {
        this.log_("Browser went offline.  Killing connection.");
        if (this.realtime_) {
          this.realtime_.close();
        }
      }
    }
    onRealtimeDisconnect_() {
      this.log_("data client disconnected");
      this.connected_ = false;
      this.realtime_ = null;
      this.cancelSentTransactions_();
      this.requestCBHash_ = {};
      if (this.shouldReconnect_()) {
        if (!this.visible_) {
          this.log_("Window isn't visible.  Delaying reconnect.");
          this.reconnectDelay_ = this.maxReconnectDelay_;
          this.lastConnectionAttemptTime_ = (/* @__PURE__ */ new Date()).getTime();
        } else if (this.lastConnectionEstablishedTime_) {
          const timeSinceLastConnectSucceeded = (/* @__PURE__ */ new Date()).getTime() - this.lastConnectionEstablishedTime_;
          if (timeSinceLastConnectSucceeded > RECONNECT_DELAY_RESET_TIMEOUT) {
            this.reconnectDelay_ = RECONNECT_MIN_DELAY;
          }
          this.lastConnectionEstablishedTime_ = null;
        }
        const timeSinceLastConnectAttempt = (/* @__PURE__ */ new Date()).getTime() - this.lastConnectionAttemptTime_;
        let reconnectDelay = Math.max(0, this.reconnectDelay_ - timeSinceLastConnectAttempt);
        reconnectDelay = Math.random() * reconnectDelay;
        this.log_("Trying to reconnect in " + reconnectDelay + "ms");
        this.scheduleConnect_(reconnectDelay);
        this.reconnectDelay_ = Math.min(this.maxReconnectDelay_, this.reconnectDelay_ * RECONNECT_DELAY_MULTIPLIER);
      }
      this.onConnectStatus_(false);
    }
    async establishConnection_() {
      if (this.shouldReconnect_()) {
        this.log_("Making a connection attempt");
        this.lastConnectionAttemptTime_ = (/* @__PURE__ */ new Date()).getTime();
        this.lastConnectionEstablishedTime_ = null;
        const onDataMessage = this.onDataMessage_.bind(this);
        const onReady = this.onReady_.bind(this);
        const onDisconnect = this.onRealtimeDisconnect_.bind(this);
        const connId = this.id + ":" + PersistentConnection.nextConnectionId_++;
        const lastSessionId = this.lastSessionId;
        let canceled = false;
        let connection = null;
        const closeFn = function() {
          if (connection) {
            connection.close();
          } else {
            canceled = true;
            onDisconnect();
          }
        };
        const sendRequestFn = function(msg) {
          assert(connection, "sendRequest call when we're not connected not allowed.");
          connection.sendRequest(msg);
        };
        this.realtime_ = {
          close: closeFn,
          sendRequest: sendRequestFn
        };
        const forceRefresh = this.forceTokenRefresh_;
        this.forceTokenRefresh_ = false;
        try {
          const [authToken, appCheckToken] = await Promise.all([
            this.authTokenProvider_.getToken(forceRefresh),
            this.appCheckTokenProvider_.getToken(forceRefresh)
          ]);
          if (!canceled) {
            log("getToken() completed. Creating connection.");
            this.authToken_ = authToken && authToken.accessToken;
            this.appCheckToken_ = appCheckToken && appCheckToken.token;
            connection = new Connection(
              connId,
              this.repoInfo_,
              this.applicationId_,
              this.appCheckToken_,
              this.authToken_,
              onDataMessage,
              onReady,
              onDisconnect,
              /* onKill= */
              (reason) => {
                warn(reason + " (" + this.repoInfo_.toString() + ")");
                this.interrupt(SERVER_KILL_INTERRUPT_REASON);
              },
              lastSessionId
            );
          } else {
            log("getToken() completed but was canceled");
          }
        } catch (error2) {
          this.log_("Failed to get token: " + error2);
          if (!canceled) {
            if (this.repoInfo_.nodeAdmin) {
              warn(error2);
            }
            closeFn();
          }
        }
      }
    }
    interrupt(reason) {
      log("Interrupting connection for reason: " + reason);
      this.interruptReasons_[reason] = true;
      if (this.realtime_) {
        this.realtime_.close();
      } else {
        if (this.establishConnectionTimer_) {
          clearTimeout(this.establishConnectionTimer_);
          this.establishConnectionTimer_ = null;
        }
        if (this.connected_) {
          this.onRealtimeDisconnect_();
        }
      }
    }
    resume(reason) {
      log("Resuming connection for reason: " + reason);
      delete this.interruptReasons_[reason];
      if (isEmpty(this.interruptReasons_)) {
        this.reconnectDelay_ = RECONNECT_MIN_DELAY;
        if (!this.realtime_) {
          this.scheduleConnect_(0);
        }
      }
    }
    handleTimestamp_(timestamp) {
      const delta = timestamp - (/* @__PURE__ */ new Date()).getTime();
      this.onServerInfoUpdate_({ serverTimeOffset: delta });
    }
    cancelSentTransactions_() {
      for (let i2 = 0; i2 < this.outstandingPuts_.length; i2++) {
        const put = this.outstandingPuts_[i2];
        if (put && /*hash*/
        "h" in put.request && put.queued) {
          if (put.onComplete) {
            put.onComplete("disconnect");
          }
          delete this.outstandingPuts_[i2];
          this.outstandingPutCount_--;
        }
      }
      if (this.outstandingPutCount_ === 0) {
        this.outstandingPuts_ = [];
      }
    }
    onListenRevoked_(pathString, query) {
      let queryId;
      if (!query) {
        queryId = "default";
      } else {
        queryId = query.map((q2) => ObjectToUniqueKey(q2)).join("$");
      }
      const listen = this.removeListen_(pathString, queryId);
      if (listen && listen.onComplete) {
        listen.onComplete("permission_denied");
      }
    }
    removeListen_(pathString, queryId) {
      const normalizedPathString = new Path(pathString).toString();
      let listen;
      if (this.listens.has(normalizedPathString)) {
        const map2 = this.listens.get(normalizedPathString);
        listen = map2.get(queryId);
        map2.delete(queryId);
        if (map2.size === 0) {
          this.listens.delete(normalizedPathString);
        }
      } else {
        listen = void 0;
      }
      return listen;
    }
    onAuthRevoked_(statusCode, explanation) {
      log("Auth token revoked: " + statusCode + "/" + explanation);
      this.authToken_ = null;
      this.forceTokenRefresh_ = true;
      this.realtime_.close();
      if (statusCode === "invalid_token" || statusCode === "permission_denied") {
        this.invalidAuthTokenCount_++;
        if (this.invalidAuthTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
          this.reconnectDelay_ = RECONNECT_MAX_DELAY_FOR_ADMINS;
          this.authTokenProvider_.notifyForInvalidToken();
        }
      }
    }
    onAppCheckRevoked_(statusCode, explanation) {
      log("App check token revoked: " + statusCode + "/" + explanation);
      this.appCheckToken_ = null;
      this.forceTokenRefresh_ = true;
      if (statusCode === "invalid_token" || statusCode === "permission_denied") {
        this.invalidAppCheckTokenCount_++;
        if (this.invalidAppCheckTokenCount_ >= INVALID_TOKEN_THRESHOLD) {
          this.appCheckTokenProvider_.notifyForInvalidToken();
        }
      }
    }
    onSecurityDebugPacket_(body) {
      if (this.securityDebugCallback_) {
        this.securityDebugCallback_(body);
      } else {
        if ("msg" in body) {
          console.log("FIREBASE: " + body["msg"].replace("\n", "\nFIREBASE: "));
        }
      }
    }
    restoreState_() {
      this.tryAuth();
      this.tryAppCheck();
      for (const queries of this.listens.values()) {
        for (const listenSpec of queries.values()) {
          this.sendListen_(listenSpec);
        }
      }
      for (let i2 = 0; i2 < this.outstandingPuts_.length; i2++) {
        if (this.outstandingPuts_[i2]) {
          this.sendPut_(i2);
        }
      }
      while (this.onDisconnectRequestQueue_.length) {
        const request = this.onDisconnectRequestQueue_.shift();
        this.sendOnDisconnect_(request.action, request.pathString, request.data, request.onComplete);
      }
      for (let i2 = 0; i2 < this.outstandingGets_.length; i2++) {
        if (this.outstandingGets_[i2]) {
          this.sendGet_(i2);
        }
      }
    }
    /**
     * Sends client stats for first connection
     */
    sendConnectStats_() {
      const stats = {};
      let clientName = "js";
      stats["sdk." + clientName + "." + SDK_VERSION.replace(/\./g, "-")] = 1;
      if (isMobileCordova()) {
        stats["framework.cordova"] = 1;
      } else if (isReactNative()) {
        stats["framework.reactnative"] = 1;
      }
      this.reportStats(stats);
    }
    shouldReconnect_() {
      const online = OnlineMonitor.getInstance().currentlyOnline();
      return isEmpty(this.interruptReasons_) && online;
    }
  }
  PersistentConnection.nextPersistentConnectionId_ = 0;
  PersistentConnection.nextConnectionId_ = 0;
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class NamedNode {
    constructor(name2, node) {
      this.name = name2;
      this.node = node;
    }
    static Wrap(name2, node) {
      return new NamedNode(name2, node);
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class Index {
    /**
     * @returns A standalone comparison function for
     * this index
     */
    getCompare() {
      return this.compare.bind(this);
    }
    /**
     * Given a before and after value for a node, determine if the indexed value has changed. Even if they are different,
     * it's possible that the changes are isolated to parts of the snapshot that are not indexed.
     *
     *
     * @returns True if the portion of the snapshot being indexed changed between oldNode and newNode
     */
    indexedValueChanged(oldNode, newNode) {
      const oldWrapped = new NamedNode(MIN_NAME, oldNode);
      const newWrapped = new NamedNode(MIN_NAME, newNode);
      return this.compare(oldWrapped, newWrapped) !== 0;
    }
    /**
     * @returns a node wrapper that will sort equal to or less than
     * any other node wrapper, using this index
     */
    minPost() {
      return NamedNode.MIN;
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  let __EMPTY_NODE;
  class KeyIndex extends Index {
    static get __EMPTY_NODE() {
      return __EMPTY_NODE;
    }
    static set __EMPTY_NODE(val) {
      __EMPTY_NODE = val;
    }
    compare(a2, b2) {
      return nameCompare(a2.name, b2.name);
    }
    isDefinedOn(node) {
      throw assertionError("KeyIndex.isDefinedOn not expected to be called.");
    }
    indexedValueChanged(oldNode, newNode) {
      return false;
    }
    minPost() {
      return NamedNode.MIN;
    }
    maxPost() {
      return new NamedNode(MAX_NAME, __EMPTY_NODE);
    }
    makePost(indexValue, name2) {
      assert(typeof indexValue === "string", "KeyIndex indexValue must always be a string.");
      return new NamedNode(indexValue, __EMPTY_NODE);
    }
    /**
     * @returns String representation for inclusion in a query spec
     */
    toString() {
      return ".key";
    }
  }
  const KEY_INDEX = new KeyIndex();
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class SortedMapIterator {
    /**
     * @param node - Node to iterate.
     * @param isReverse_ - Whether or not to iterate in reverse
     */
    constructor(node, startKey, comparator, isReverse_, resultGenerator_ = null) {
      this.isReverse_ = isReverse_;
      this.resultGenerator_ = resultGenerator_;
      this.nodeStack_ = [];
      let cmp = 1;
      while (!node.isEmpty()) {
        node = node;
        cmp = startKey ? comparator(node.key, startKey) : 1;
        if (isReverse_) {
          cmp *= -1;
        }
        if (cmp < 0) {
          if (this.isReverse_) {
            node = node.left;
          } else {
            node = node.right;
          }
        } else if (cmp === 0) {
          this.nodeStack_.push(node);
          break;
        } else {
          this.nodeStack_.push(node);
          if (this.isReverse_) {
            node = node.right;
          } else {
            node = node.left;
          }
        }
      }
    }
    getNext() {
      if (this.nodeStack_.length === 0) {
        return null;
      }
      let node = this.nodeStack_.pop();
      let result;
      if (this.resultGenerator_) {
        result = this.resultGenerator_(node.key, node.value);
      } else {
        result = { key: node.key, value: node.value };
      }
      if (this.isReverse_) {
        node = node.left;
        while (!node.isEmpty()) {
          this.nodeStack_.push(node);
          node = node.right;
        }
      } else {
        node = node.right;
        while (!node.isEmpty()) {
          this.nodeStack_.push(node);
          node = node.left;
        }
      }
      return result;
    }
    hasNext() {
      return this.nodeStack_.length > 0;
    }
    peek() {
      if (this.nodeStack_.length === 0) {
        return null;
      }
      const node = this.nodeStack_[this.nodeStack_.length - 1];
      if (this.resultGenerator_) {
        return this.resultGenerator_(node.key, node.value);
      } else {
        return { key: node.key, value: node.value };
      }
    }
  }
  class LLRBNode {
    /**
     * @param key - Key associated with this node.
     * @param value - Value associated with this node.
     * @param color - Whether this node is red.
     * @param left - Left child.
     * @param right - Right child.
     */
    constructor(key, value, color, left, right) {
      this.key = key;
      this.value = value;
      this.color = color != null ? color : LLRBNode.RED;
      this.left = left != null ? left : SortedMap.EMPTY_NODE;
      this.right = right != null ? right : SortedMap.EMPTY_NODE;
    }
    /**
     * Returns a copy of the current node, optionally replacing pieces of it.
     *
     * @param key - New key for the node, or null.
     * @param value - New value for the node, or null.
     * @param color - New color for the node, or null.
     * @param left - New left child for the node, or null.
     * @param right - New right child for the node, or null.
     * @returns The node copy.
     */
    copy(key, value, color, left, right) {
      return new LLRBNode(key != null ? key : this.key, value != null ? value : this.value, color != null ? color : this.color, left != null ? left : this.left, right != null ? right : this.right);
    }
    /**
     * @returns The total number of nodes in the tree.
     */
    count() {
      return this.left.count() + 1 + this.right.count();
    }
    /**
     * @returns True if the tree is empty.
     */
    isEmpty() {
      return false;
    }
    /**
     * Traverses the tree in key order and calls the specified action function
     * for each node.
     *
     * @param action - Callback function to be called for each
     *   node.  If it returns true, traversal is aborted.
     * @returns The first truthy value returned by action, or the last falsey
     *   value returned by action
     */
    inorderTraversal(action) {
      return this.left.inorderTraversal(action) || !!action(this.key, this.value) || this.right.inorderTraversal(action);
    }
    /**
     * Traverses the tree in reverse key order and calls the specified action function
     * for each node.
     *
     * @param action - Callback function to be called for each
     * node.  If it returns true, traversal is aborted.
     * @returns True if traversal was aborted.
     */
    reverseTraversal(action) {
      return this.right.reverseTraversal(action) || action(this.key, this.value) || this.left.reverseTraversal(action);
    }
    /**
     * @returns The minimum node in the tree.
     */
    min_() {
      if (this.left.isEmpty()) {
        return this;
      } else {
        return this.left.min_();
      }
    }
    /**
     * @returns The maximum key in the tree.
     */
    minKey() {
      return this.min_().key;
    }
    /**
     * @returns The maximum key in the tree.
     */
    maxKey() {
      if (this.right.isEmpty()) {
        return this.key;
      } else {
        return this.right.maxKey();
      }
    }
    /**
     * @param key - Key to insert.
     * @param value - Value to insert.
     * @param comparator - Comparator.
     * @returns New tree, with the key/value added.
     */
    insert(key, value, comparator) {
      let n2 = this;
      const cmp = comparator(key, n2.key);
      if (cmp < 0) {
        n2 = n2.copy(null, null, null, n2.left.insert(key, value, comparator), null);
      } else if (cmp === 0) {
        n2 = n2.copy(null, value, null, null, null);
      } else {
        n2 = n2.copy(null, null, null, null, n2.right.insert(key, value, comparator));
      }
      return n2.fixUp_();
    }
    /**
     * @returns New tree, with the minimum key removed.
     */
    removeMin_() {
      if (this.left.isEmpty()) {
        return SortedMap.EMPTY_NODE;
      }
      let n2 = this;
      if (!n2.left.isRed_() && !n2.left.left.isRed_()) {
        n2 = n2.moveRedLeft_();
      }
      n2 = n2.copy(null, null, null, n2.left.removeMin_(), null);
      return n2.fixUp_();
    }
    /**
     * @param key - The key of the item to remove.
     * @param comparator - Comparator.
     * @returns New tree, with the specified item removed.
     */
    remove(key, comparator) {
      let n2, smallest;
      n2 = this;
      if (comparator(key, n2.key) < 0) {
        if (!n2.left.isEmpty() && !n2.left.isRed_() && !n2.left.left.isRed_()) {
          n2 = n2.moveRedLeft_();
        }
        n2 = n2.copy(null, null, null, n2.left.remove(key, comparator), null);
      } else {
        if (n2.left.isRed_()) {
          n2 = n2.rotateRight_();
        }
        if (!n2.right.isEmpty() && !n2.right.isRed_() && !n2.right.left.isRed_()) {
          n2 = n2.moveRedRight_();
        }
        if (comparator(key, n2.key) === 0) {
          if (n2.right.isEmpty()) {
            return SortedMap.EMPTY_NODE;
          } else {
            smallest = n2.right.min_();
            n2 = n2.copy(smallest.key, smallest.value, null, null, n2.right.removeMin_());
          }
        }
        n2 = n2.copy(null, null, null, null, n2.right.remove(key, comparator));
      }
      return n2.fixUp_();
    }
    /**
     * @returns Whether this is a RED node.
     */
    isRed_() {
      return this.color;
    }
    /**
     * @returns New tree after performing any needed rotations.
     */
    fixUp_() {
      let n2 = this;
      if (n2.right.isRed_() && !n2.left.isRed_()) {
        n2 = n2.rotateLeft_();
      }
      if (n2.left.isRed_() && n2.left.left.isRed_()) {
        n2 = n2.rotateRight_();
      }
      if (n2.left.isRed_() && n2.right.isRed_()) {
        n2 = n2.colorFlip_();
      }
      return n2;
    }
    /**
     * @returns New tree, after moveRedLeft.
     */
    moveRedLeft_() {
      let n2 = this.colorFlip_();
      if (n2.right.left.isRed_()) {
        n2 = n2.copy(null, null, null, null, n2.right.rotateRight_());
        n2 = n2.rotateLeft_();
        n2 = n2.colorFlip_();
      }
      return n2;
    }
    /**
     * @returns New tree, after moveRedRight.
     */
    moveRedRight_() {
      let n2 = this.colorFlip_();
      if (n2.left.left.isRed_()) {
        n2 = n2.rotateRight_();
        n2 = n2.colorFlip_();
      }
      return n2;
    }
    /**
     * @returns New tree, after rotateLeft.
     */
    rotateLeft_() {
      const nl = this.copy(null, null, LLRBNode.RED, null, this.right.left);
      return this.right.copy(null, null, this.color, nl, null);
    }
    /**
     * @returns New tree, after rotateRight.
     */
    rotateRight_() {
      const nr = this.copy(null, null, LLRBNode.RED, this.left.right, null);
      return this.left.copy(null, null, this.color, null, nr);
    }
    /**
     * @returns Newt ree, after colorFlip.
     */
    colorFlip_() {
      const left = this.left.copy(null, null, !this.left.color, null, null);
      const right = this.right.copy(null, null, !this.right.color, null, null);
      return this.copy(null, null, !this.color, left, right);
    }
    /**
     * For testing.
     *
     * @returns True if all is well.
     */
    checkMaxDepth_() {
      const blackDepth = this.check_();
      return Math.pow(2, blackDepth) <= this.count() + 1;
    }
    check_() {
      if (this.isRed_() && this.left.isRed_()) {
        throw new Error("Red node has red child(" + this.key + "," + this.value + ")");
      }
      if (this.right.isRed_()) {
        throw new Error("Right child of (" + this.key + "," + this.value + ") is red");
      }
      const blackDepth = this.left.check_();
      if (blackDepth !== this.right.check_()) {
        throw new Error("Black depths differ");
      } else {
        return blackDepth + (this.isRed_() ? 0 : 1);
      }
    }
  }
  LLRBNode.RED = true;
  LLRBNode.BLACK = false;
  class LLRBEmptyNode {
    /**
     * Returns a copy of the current node.
     *
     * @returns The node copy.
     */
    copy(key, value, color, left, right) {
      return this;
    }
    /**
     * Returns a copy of the tree, with the specified key/value added.
     *
     * @param key - Key to be added.
     * @param value - Value to be added.
     * @param comparator - Comparator.
     * @returns New tree, with item added.
     */
    insert(key, value, comparator) {
      return new LLRBNode(key, value, null);
    }
    /**
     * Returns a copy of the tree, with the specified key removed.
     *
     * @param key - The key to remove.
     * @param comparator - Comparator.
     * @returns New tree, with item removed.
     */
    remove(key, comparator) {
      return this;
    }
    /**
     * @returns The total number of nodes in the tree.
     */
    count() {
      return 0;
    }
    /**
     * @returns True if the tree is empty.
     */
    isEmpty() {
      return true;
    }
    /**
     * Traverses the tree in key order and calls the specified action function
     * for each node.
     *
     * @param action - Callback function to be called for each
     * node.  If it returns true, traversal is aborted.
     * @returns True if traversal was aborted.
     */
    inorderTraversal(action) {
      return false;
    }
    /**
     * Traverses the tree in reverse key order and calls the specified action function
     * for each node.
     *
     * @param action - Callback function to be called for each
     * node.  If it returns true, traversal is aborted.
     * @returns True if traversal was aborted.
     */
    reverseTraversal(action) {
      return false;
    }
    minKey() {
      return null;
    }
    maxKey() {
      return null;
    }
    check_() {
      return 0;
    }
    /**
     * @returns Whether this node is red.
     */
    isRed_() {
      return false;
    }
  }
  class SortedMap {
    /**
     * @param comparator_ - Key comparator.
     * @param root_ - Optional root node for the map.
     */
    constructor(comparator_, root_ = SortedMap.EMPTY_NODE) {
      this.comparator_ = comparator_;
      this.root_ = root_;
    }
    /**
     * Returns a copy of the map, with the specified key/value added or replaced.
     * (TODO: We should perhaps rename this method to 'put')
     *
     * @param key - Key to be added.
     * @param value - Value to be added.
     * @returns New map, with item added.
     */
    insert(key, value) {
      return new SortedMap(this.comparator_, this.root_.insert(key, value, this.comparator_).copy(null, null, LLRBNode.BLACK, null, null));
    }
    /**
     * Returns a copy of the map, with the specified key removed.
     *
     * @param key - The key to remove.
     * @returns New map, with item removed.
     */
    remove(key) {
      return new SortedMap(this.comparator_, this.root_.remove(key, this.comparator_).copy(null, null, LLRBNode.BLACK, null, null));
    }
    /**
     * Returns the value of the node with the given key, or null.
     *
     * @param key - The key to look up.
     * @returns The value of the node with the given key, or null if the
     * key doesn't exist.
     */
    get(key) {
      let cmp;
      let node = this.root_;
      while (!node.isEmpty()) {
        cmp = this.comparator_(key, node.key);
        if (cmp === 0) {
          return node.value;
        } else if (cmp < 0) {
          node = node.left;
        } else if (cmp > 0) {
          node = node.right;
        }
      }
      return null;
    }
    /**
     * Returns the key of the item *before* the specified key, or null if key is the first item.
     * @param key - The key to find the predecessor of
     * @returns The predecessor key.
     */
    getPredecessorKey(key) {
      let cmp, node = this.root_, rightParent = null;
      while (!node.isEmpty()) {
        cmp = this.comparator_(key, node.key);
        if (cmp === 0) {
          if (!node.left.isEmpty()) {
            node = node.left;
            while (!node.right.isEmpty()) {
              node = node.right;
            }
            return node.key;
          } else if (rightParent) {
            return rightParent.key;
          } else {
            return null;
          }
        } else if (cmp < 0) {
          node = node.left;
        } else if (cmp > 0) {
          rightParent = node;
          node = node.right;
        }
      }
      throw new Error("Attempted to find predecessor key for a nonexistent key.  What gives?");
    }
    /**
     * @returns True if the map is empty.
     */
    isEmpty() {
      return this.root_.isEmpty();
    }
    /**
     * @returns The total number of nodes in the map.
     */
    count() {
      return this.root_.count();
    }
    /**
     * @returns The minimum key in the map.
     */
    minKey() {
      return this.root_.minKey();
    }
    /**
     * @returns The maximum key in the map.
     */
    maxKey() {
      return this.root_.maxKey();
    }
    /**
     * Traverses the map in key order and calls the specified action function
     * for each key/value pair.
     *
     * @param action - Callback function to be called
     * for each key/value pair.  If action returns true, traversal is aborted.
     * @returns The first truthy value returned by action, or the last falsey
     *   value returned by action
     */
    inorderTraversal(action) {
      return this.root_.inorderTraversal(action);
    }
    /**
     * Traverses the map in reverse key order and calls the specified action function
     * for each key/value pair.
     *
     * @param action - Callback function to be called
     * for each key/value pair.  If action returns true, traversal is aborted.
     * @returns True if the traversal was aborted.
     */
    reverseTraversal(action) {
      return this.root_.reverseTraversal(action);
    }
    /**
     * Returns an iterator over the SortedMap.
     * @returns The iterator.
     */
    getIterator(resultGenerator) {
      return new SortedMapIterator(this.root_, null, this.comparator_, false, resultGenerator);
    }
    getIteratorFrom(key, resultGenerator) {
      return new SortedMapIterator(this.root_, key, this.comparator_, false, resultGenerator);
    }
    getReverseIteratorFrom(key, resultGenerator) {
      return new SortedMapIterator(this.root_, key, this.comparator_, true, resultGenerator);
    }
    getReverseIterator(resultGenerator) {
      return new SortedMapIterator(this.root_, null, this.comparator_, true, resultGenerator);
    }
  }
  SortedMap.EMPTY_NODE = new LLRBEmptyNode();
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function NAME_ONLY_COMPARATOR(left, right) {
    return nameCompare(left.name, right.name);
  }
  function NAME_COMPARATOR(left, right) {
    return nameCompare(left, right);
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  let MAX_NODE$2;
  function setMaxNode$1(val) {
    MAX_NODE$2 = val;
  }
  const priorityHashText = function(priority) {
    if (typeof priority === "number") {
      return "number:" + doubleToIEEE754String(priority);
    } else {
      return "string:" + priority;
    }
  };
  const validatePriorityNode = function(priorityNode) {
    if (priorityNode.isLeafNode()) {
      const val = priorityNode.val();
      assert(typeof val === "string" || typeof val === "number" || typeof val === "object" && contains(val, ".sv"), "Priority must be a string or number.");
    } else {
      assert(priorityNode === MAX_NODE$2 || priorityNode.isEmpty(), "priority of unexpected type.");
    }
    assert(priorityNode === MAX_NODE$2 || priorityNode.getPriority().isEmpty(), "Priority nodes can't have a priority of their own.");
  };
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  let __childrenNodeConstructor;
  class LeafNode {
    /**
     * @param value_ - The value to store in this leaf node. The object type is
     * possible in the event of a deferred value
     * @param priorityNode_ - The priority of this node.
     */
    constructor(value_, priorityNode_ = LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
      this.value_ = value_;
      this.priorityNode_ = priorityNode_;
      this.lazyHash_ = null;
      assert(this.value_ !== void 0 && this.value_ !== null, "LeafNode shouldn't be created with null/undefined value.");
      validatePriorityNode(this.priorityNode_);
    }
    static set __childrenNodeConstructor(val) {
      __childrenNodeConstructor = val;
    }
    static get __childrenNodeConstructor() {
      return __childrenNodeConstructor;
    }
    /** @inheritDoc */
    isLeafNode() {
      return true;
    }
    /** @inheritDoc */
    getPriority() {
      return this.priorityNode_;
    }
    /** @inheritDoc */
    updatePriority(newPriorityNode) {
      return new LeafNode(this.value_, newPriorityNode);
    }
    /** @inheritDoc */
    getImmediateChild(childName) {
      if (childName === ".priority") {
        return this.priorityNode_;
      } else {
        return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
      }
    }
    /** @inheritDoc */
    getChild(path) {
      if (pathIsEmpty(path)) {
        return this;
      } else if (pathGetFront(path) === ".priority") {
        return this.priorityNode_;
      } else {
        return LeafNode.__childrenNodeConstructor.EMPTY_NODE;
      }
    }
    hasChild() {
      return false;
    }
    /** @inheritDoc */
    getPredecessorChildName(childName, childNode) {
      return null;
    }
    /** @inheritDoc */
    updateImmediateChild(childName, newChildNode) {
      if (childName === ".priority") {
        return this.updatePriority(newChildNode);
      } else if (newChildNode.isEmpty() && childName !== ".priority") {
        return this;
      } else {
        return LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateImmediateChild(childName, newChildNode).updatePriority(this.priorityNode_);
      }
    }
    /** @inheritDoc */
    updateChild(path, newChildNode) {
      const front = pathGetFront(path);
      if (front === null) {
        return newChildNode;
      } else if (newChildNode.isEmpty() && front !== ".priority") {
        return this;
      } else {
        assert(front !== ".priority" || pathGetLength(path) === 1, ".priority must be the last token in a path");
        return this.updateImmediateChild(front, LeafNode.__childrenNodeConstructor.EMPTY_NODE.updateChild(pathPopFront(path), newChildNode));
      }
    }
    /** @inheritDoc */
    isEmpty() {
      return false;
    }
    /** @inheritDoc */
    numChildren() {
      return 0;
    }
    /** @inheritDoc */
    forEachChild(index2, action) {
      return false;
    }
    val(exportFormat) {
      if (exportFormat && !this.getPriority().isEmpty()) {
        return {
          ".value": this.getValue(),
          ".priority": this.getPriority().val()
        };
      } else {
        return this.getValue();
      }
    }
    /** @inheritDoc */
    hash() {
      if (this.lazyHash_ === null) {
        let toHash = "";
        if (!this.priorityNode_.isEmpty()) {
          toHash += "priority:" + priorityHashText(this.priorityNode_.val()) + ":";
        }
        const type = typeof this.value_;
        toHash += type + ":";
        if (type === "number") {
          toHash += doubleToIEEE754String(this.value_);
        } else {
          toHash += this.value_;
        }
        this.lazyHash_ = sha1(toHash);
      }
      return this.lazyHash_;
    }
    /**
     * Returns the value of the leaf node.
     * @returns The value of the node.
     */
    getValue() {
      return this.value_;
    }
    compareTo(other) {
      if (other === LeafNode.__childrenNodeConstructor.EMPTY_NODE) {
        return 1;
      } else if (other instanceof LeafNode.__childrenNodeConstructor) {
        return -1;
      } else {
        assert(other.isLeafNode(), "Unknown node type");
        return this.compareToLeafNode_(other);
      }
    }
    /**
     * Comparison specifically for two leaf nodes
     */
    compareToLeafNode_(otherLeaf) {
      const otherLeafType = typeof otherLeaf.value_;
      const thisLeafType = typeof this.value_;
      const otherIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(otherLeafType);
      const thisIndex = LeafNode.VALUE_TYPE_ORDER.indexOf(thisLeafType);
      assert(otherIndex >= 0, "Unknown leaf type: " + otherLeafType);
      assert(thisIndex >= 0, "Unknown leaf type: " + thisLeafType);
      if (otherIndex === thisIndex) {
        if (thisLeafType === "object") {
          return 0;
        } else {
          if (this.value_ < otherLeaf.value_) {
            return -1;
          } else if (this.value_ === otherLeaf.value_) {
            return 0;
          } else {
            return 1;
          }
        }
      } else {
        return thisIndex - otherIndex;
      }
    }
    withIndex() {
      return this;
    }
    isIndexed() {
      return true;
    }
    equals(other) {
      if (other === this) {
        return true;
      } else if (other.isLeafNode()) {
        const otherLeaf = other;
        return this.value_ === otherLeaf.value_ && this.priorityNode_.equals(otherLeaf.priorityNode_);
      } else {
        return false;
      }
    }
  }
  LeafNode.VALUE_TYPE_ORDER = ["object", "boolean", "number", "string"];
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  let nodeFromJSON$1;
  let MAX_NODE$1;
  function setNodeFromJSON(val) {
    nodeFromJSON$1 = val;
  }
  function setMaxNode(val) {
    MAX_NODE$1 = val;
  }
  class PriorityIndex extends Index {
    compare(a2, b2) {
      const aPriority = a2.node.getPriority();
      const bPriority = b2.node.getPriority();
      const indexCmp = aPriority.compareTo(bPriority);
      if (indexCmp === 0) {
        return nameCompare(a2.name, b2.name);
      } else {
        return indexCmp;
      }
    }
    isDefinedOn(node) {
      return !node.getPriority().isEmpty();
    }
    indexedValueChanged(oldNode, newNode) {
      return !oldNode.getPriority().equals(newNode.getPriority());
    }
    minPost() {
      return NamedNode.MIN;
    }
    maxPost() {
      return new NamedNode(MAX_NAME, new LeafNode("[PRIORITY-POST]", MAX_NODE$1));
    }
    makePost(indexValue, name2) {
      const priorityNode = nodeFromJSON$1(indexValue);
      return new NamedNode(name2, new LeafNode("[PRIORITY-POST]", priorityNode));
    }
    /**
     * @returns String representation for inclusion in a query spec
     */
    toString() {
      return ".priority";
    }
  }
  const PRIORITY_INDEX = new PriorityIndex();
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const LOG_2 = Math.log(2);
  class Base12Num {
    constructor(length) {
      const logBase2 = (num) => (
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        parseInt(Math.log(num) / LOG_2, 10)
      );
      const bitMask = (bits) => parseInt(Array(bits + 1).join("1"), 2);
      this.count = logBase2(length + 1);
      this.current_ = this.count - 1;
      const mask = bitMask(this.count);
      this.bits_ = length + 1 & mask;
    }
    nextBitIsOne() {
      const result = !(this.bits_ & 1 << this.current_);
      this.current_--;
      return result;
    }
  }
  const buildChildSet = function(childList, cmp, keyFn, mapSortFn) {
    childList.sort(cmp);
    const buildBalancedTree = function(low, high) {
      const length = high - low;
      let namedNode;
      let key;
      if (length === 0) {
        return null;
      } else if (length === 1) {
        namedNode = childList[low];
        key = keyFn ? keyFn(namedNode) : namedNode;
        return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, null, null);
      } else {
        const middle = parseInt(length / 2, 10) + low;
        const left = buildBalancedTree(low, middle);
        const right = buildBalancedTree(middle + 1, high);
        namedNode = childList[middle];
        key = keyFn ? keyFn(namedNode) : namedNode;
        return new LLRBNode(key, namedNode.node, LLRBNode.BLACK, left, right);
      }
    };
    const buildFrom12Array = function(base122) {
      let node = null;
      let root2 = null;
      let index2 = childList.length;
      const buildPennant = function(chunkSize, color) {
        const low = index2 - chunkSize;
        const high = index2;
        index2 -= chunkSize;
        const childTree = buildBalancedTree(low + 1, high);
        const namedNode = childList[low];
        const key = keyFn ? keyFn(namedNode) : namedNode;
        attachPennant(new LLRBNode(key, namedNode.node, color, null, childTree));
      };
      const attachPennant = function(pennant) {
        if (node) {
          node.left = pennant;
          node = pennant;
        } else {
          root2 = pennant;
          node = pennant;
        }
      };
      for (let i2 = 0; i2 < base122.count; ++i2) {
        const isOne = base122.nextBitIsOne();
        const chunkSize = Math.pow(2, base122.count - (i2 + 1));
        if (isOne) {
          buildPennant(chunkSize, LLRBNode.BLACK);
        } else {
          buildPennant(chunkSize, LLRBNode.BLACK);
          buildPennant(chunkSize, LLRBNode.RED);
        }
      }
      return root2;
    };
    const base12 = new Base12Num(childList.length);
    const root = buildFrom12Array(base12);
    return new SortedMap(mapSortFn || cmp, root);
  };
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  let _defaultIndexMap;
  const fallbackObject = {};
  class IndexMap {
    constructor(indexes_, indexSet_) {
      this.indexes_ = indexes_;
      this.indexSet_ = indexSet_;
    }
    /**
     * The default IndexMap for nodes without a priority
     */
    static get Default() {
      assert(fallbackObject && PRIORITY_INDEX, "ChildrenNode.ts has not been loaded");
      _defaultIndexMap = _defaultIndexMap || new IndexMap({ ".priority": fallbackObject }, { ".priority": PRIORITY_INDEX });
      return _defaultIndexMap;
    }
    get(indexKey) {
      const sortedMap = safeGet(this.indexes_, indexKey);
      if (!sortedMap) {
        throw new Error("No index defined for " + indexKey);
      }
      if (sortedMap instanceof SortedMap) {
        return sortedMap;
      } else {
        return null;
      }
    }
    hasIndex(indexDefinition) {
      return contains(this.indexSet_, indexDefinition.toString());
    }
    addIndex(indexDefinition, existingChildren) {
      assert(indexDefinition !== KEY_INDEX, "KeyIndex always exists and isn't meant to be added to the IndexMap.");
      const childList = [];
      let sawIndexedValue = false;
      const iter = existingChildren.getIterator(NamedNode.Wrap);
      let next = iter.getNext();
      while (next) {
        sawIndexedValue = sawIndexedValue || indexDefinition.isDefinedOn(next.node);
        childList.push(next);
        next = iter.getNext();
      }
      let newIndex;
      if (sawIndexedValue) {
        newIndex = buildChildSet(childList, indexDefinition.getCompare());
      } else {
        newIndex = fallbackObject;
      }
      const indexName = indexDefinition.toString();
      const newIndexSet = Object.assign({}, this.indexSet_);
      newIndexSet[indexName] = indexDefinition;
      const newIndexes = Object.assign({}, this.indexes_);
      newIndexes[indexName] = newIndex;
      return new IndexMap(newIndexes, newIndexSet);
    }
    /**
     * Ensure that this node is properly tracked in any indexes that we're maintaining
     */
    addToIndexes(namedNode, existingChildren) {
      const newIndexes = map(this.indexes_, (indexedChildren, indexName) => {
        const index2 = safeGet(this.indexSet_, indexName);
        assert(index2, "Missing index implementation for " + indexName);
        if (indexedChildren === fallbackObject) {
          if (index2.isDefinedOn(namedNode.node)) {
            const childList = [];
            const iter = existingChildren.getIterator(NamedNode.Wrap);
            let next = iter.getNext();
            while (next) {
              if (next.name !== namedNode.name) {
                childList.push(next);
              }
              next = iter.getNext();
            }
            childList.push(namedNode);
            return buildChildSet(childList, index2.getCompare());
          } else {
            return fallbackObject;
          }
        } else {
          const existingSnap = existingChildren.get(namedNode.name);
          let newChildren = indexedChildren;
          if (existingSnap) {
            newChildren = newChildren.remove(new NamedNode(namedNode.name, existingSnap));
          }
          return newChildren.insert(namedNode, namedNode.node);
        }
      });
      return new IndexMap(newIndexes, this.indexSet_);
    }
    /**
     * Create a new IndexMap instance with the given value removed
     */
    removeFromIndexes(namedNode, existingChildren) {
      const newIndexes = map(this.indexes_, (indexedChildren) => {
        if (indexedChildren === fallbackObject) {
          return indexedChildren;
        } else {
          const existingSnap = existingChildren.get(namedNode.name);
          if (existingSnap) {
            return indexedChildren.remove(new NamedNode(namedNode.name, existingSnap));
          } else {
            return indexedChildren;
          }
        }
      });
      return new IndexMap(newIndexes, this.indexSet_);
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  let EMPTY_NODE;
  class ChildrenNode {
    /**
     * @param children_ - List of children of this node..
     * @param priorityNode_ - The priority of this node (as a snapshot node).
     */
    constructor(children_, priorityNode_, indexMap_) {
      this.children_ = children_;
      this.priorityNode_ = priorityNode_;
      this.indexMap_ = indexMap_;
      this.lazyHash_ = null;
      if (this.priorityNode_) {
        validatePriorityNode(this.priorityNode_);
      }
      if (this.children_.isEmpty()) {
        assert(!this.priorityNode_ || this.priorityNode_.isEmpty(), "An empty node cannot have a priority");
      }
    }
    static get EMPTY_NODE() {
      return EMPTY_NODE || (EMPTY_NODE = new ChildrenNode(new SortedMap(NAME_COMPARATOR), null, IndexMap.Default));
    }
    /** @inheritDoc */
    isLeafNode() {
      return false;
    }
    /** @inheritDoc */
    getPriority() {
      return this.priorityNode_ || EMPTY_NODE;
    }
    /** @inheritDoc */
    updatePriority(newPriorityNode) {
      if (this.children_.isEmpty()) {
        return this;
      } else {
        return new ChildrenNode(this.children_, newPriorityNode, this.indexMap_);
      }
    }
    /** @inheritDoc */
    getImmediateChild(childName) {
      if (childName === ".priority") {
        return this.getPriority();
      } else {
        const child2 = this.children_.get(childName);
        return child2 === null ? EMPTY_NODE : child2;
      }
    }
    /** @inheritDoc */
    getChild(path) {
      const front = pathGetFront(path);
      if (front === null) {
        return this;
      }
      return this.getImmediateChild(front).getChild(pathPopFront(path));
    }
    /** @inheritDoc */
    hasChild(childName) {
      return this.children_.get(childName) !== null;
    }
    /** @inheritDoc */
    updateImmediateChild(childName, newChildNode) {
      assert(newChildNode, "We should always be passing snapshot nodes");
      if (childName === ".priority") {
        return this.updatePriority(newChildNode);
      } else {
        const namedNode = new NamedNode(childName, newChildNode);
        let newChildren, newIndexMap;
        if (newChildNode.isEmpty()) {
          newChildren = this.children_.remove(childName);
          newIndexMap = this.indexMap_.removeFromIndexes(namedNode, this.children_);
        } else {
          newChildren = this.children_.insert(childName, newChildNode);
          newIndexMap = this.indexMap_.addToIndexes(namedNode, this.children_);
        }
        const newPriority = newChildren.isEmpty() ? EMPTY_NODE : this.priorityNode_;
        return new ChildrenNode(newChildren, newPriority, newIndexMap);
      }
    }
    /** @inheritDoc */
    updateChild(path, newChildNode) {
      const front = pathGetFront(path);
      if (front === null) {
        return newChildNode;
      } else {
        assert(pathGetFront(path) !== ".priority" || pathGetLength(path) === 1, ".priority must be the last token in a path");
        const newImmediateChild = this.getImmediateChild(front).updateChild(pathPopFront(path), newChildNode);
        return this.updateImmediateChild(front, newImmediateChild);
      }
    }
    /** @inheritDoc */
    isEmpty() {
      return this.children_.isEmpty();
    }
    /** @inheritDoc */
    numChildren() {
      return this.children_.count();
    }
    /** @inheritDoc */
    val(exportFormat) {
      if (this.isEmpty()) {
        return null;
      }
      const obj = {};
      let numKeys = 0, maxKey = 0, allIntegerKeys = true;
      this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
        obj[key] = childNode.val(exportFormat);
        numKeys++;
        if (allIntegerKeys && ChildrenNode.INTEGER_REGEXP_.test(key)) {
          maxKey = Math.max(maxKey, Number(key));
        } else {
          allIntegerKeys = false;
        }
      });
      if (!exportFormat && allIntegerKeys && maxKey < 2 * numKeys) {
        const array = [];
        for (const key in obj) {
          array[key] = obj[key];
        }
        return array;
      } else {
        if (exportFormat && !this.getPriority().isEmpty()) {
          obj[".priority"] = this.getPriority().val();
        }
        return obj;
      }
    }
    /** @inheritDoc */
    hash() {
      if (this.lazyHash_ === null) {
        let toHash = "";
        if (!this.getPriority().isEmpty()) {
          toHash += "priority:" + priorityHashText(this.getPriority().val()) + ":";
        }
        this.forEachChild(PRIORITY_INDEX, (key, childNode) => {
          const childHash = childNode.hash();
          if (childHash !== "") {
            toHash += ":" + key + ":" + childHash;
          }
        });
        this.lazyHash_ = toHash === "" ? "" : sha1(toHash);
      }
      return this.lazyHash_;
    }
    /** @inheritDoc */
    getPredecessorChildName(childName, childNode, index2) {
      const idx = this.resolveIndex_(index2);
      if (idx) {
        const predecessor = idx.getPredecessorKey(new NamedNode(childName, childNode));
        return predecessor ? predecessor.name : null;
      } else {
        return this.children_.getPredecessorKey(childName);
      }
    }
    getFirstChildName(indexDefinition) {
      const idx = this.resolveIndex_(indexDefinition);
      if (idx) {
        const minKey = idx.minKey();
        return minKey && minKey.name;
      } else {
        return this.children_.minKey();
      }
    }
    getFirstChild(indexDefinition) {
      const minKey = this.getFirstChildName(indexDefinition);
      if (minKey) {
        return new NamedNode(minKey, this.children_.get(minKey));
      } else {
        return null;
      }
    }
    /**
     * Given an index, return the key name of the largest value we have, according to that index
     */
    getLastChildName(indexDefinition) {
      const idx = this.resolveIndex_(indexDefinition);
      if (idx) {
        const maxKey = idx.maxKey();
        return maxKey && maxKey.name;
      } else {
        return this.children_.maxKey();
      }
    }
    getLastChild(indexDefinition) {
      const maxKey = this.getLastChildName(indexDefinition);
      if (maxKey) {
        return new NamedNode(maxKey, this.children_.get(maxKey));
      } else {
        return null;
      }
    }
    forEachChild(index2, action) {
      const idx = this.resolveIndex_(index2);
      if (idx) {
        return idx.inorderTraversal((wrappedNode) => {
          return action(wrappedNode.name, wrappedNode.node);
        });
      } else {
        return this.children_.inorderTraversal(action);
      }
    }
    getIterator(indexDefinition) {
      return this.getIteratorFrom(indexDefinition.minPost(), indexDefinition);
    }
    getIteratorFrom(startPost, indexDefinition) {
      const idx = this.resolveIndex_(indexDefinition);
      if (idx) {
        return idx.getIteratorFrom(startPost, (key) => key);
      } else {
        const iterator = this.children_.getIteratorFrom(startPost.name, NamedNode.Wrap);
        let next = iterator.peek();
        while (next != null && indexDefinition.compare(next, startPost) < 0) {
          iterator.getNext();
          next = iterator.peek();
        }
        return iterator;
      }
    }
    getReverseIterator(indexDefinition) {
      return this.getReverseIteratorFrom(indexDefinition.maxPost(), indexDefinition);
    }
    getReverseIteratorFrom(endPost, indexDefinition) {
      const idx = this.resolveIndex_(indexDefinition);
      if (idx) {
        return idx.getReverseIteratorFrom(endPost, (key) => {
          return key;
        });
      } else {
        const iterator = this.children_.getReverseIteratorFrom(endPost.name, NamedNode.Wrap);
        let next = iterator.peek();
        while (next != null && indexDefinition.compare(next, endPost) > 0) {
          iterator.getNext();
          next = iterator.peek();
        }
        return iterator;
      }
    }
    compareTo(other) {
      if (this.isEmpty()) {
        if (other.isEmpty()) {
          return 0;
        } else {
          return -1;
        }
      } else if (other.isLeafNode() || other.isEmpty()) {
        return 1;
      } else if (other === MAX_NODE) {
        return -1;
      } else {
        return 0;
      }
    }
    withIndex(indexDefinition) {
      if (indexDefinition === KEY_INDEX || this.indexMap_.hasIndex(indexDefinition)) {
        return this;
      } else {
        const newIndexMap = this.indexMap_.addIndex(indexDefinition, this.children_);
        return new ChildrenNode(this.children_, this.priorityNode_, newIndexMap);
      }
    }
    isIndexed(index2) {
      return index2 === KEY_INDEX || this.indexMap_.hasIndex(index2);
    }
    equals(other) {
      if (other === this) {
        return true;
      } else if (other.isLeafNode()) {
        return false;
      } else {
        const otherChildrenNode = other;
        if (!this.getPriority().equals(otherChildrenNode.getPriority())) {
          return false;
        } else if (this.children_.count() === otherChildrenNode.children_.count()) {
          const thisIter = this.getIterator(PRIORITY_INDEX);
          const otherIter = otherChildrenNode.getIterator(PRIORITY_INDEX);
          let thisCurrent = thisIter.getNext();
          let otherCurrent = otherIter.getNext();
          while (thisCurrent && otherCurrent) {
            if (thisCurrent.name !== otherCurrent.name || !thisCurrent.node.equals(otherCurrent.node)) {
              return false;
            }
            thisCurrent = thisIter.getNext();
            otherCurrent = otherIter.getNext();
          }
          return thisCurrent === null && otherCurrent === null;
        } else {
          return false;
        }
      }
    }
    /**
     * Returns a SortedMap ordered by index, or null if the default (by-key) ordering can be used
     * instead.
     *
     */
    resolveIndex_(indexDefinition) {
      if (indexDefinition === KEY_INDEX) {
        return null;
      } else {
        return this.indexMap_.get(indexDefinition.toString());
      }
    }
  }
  ChildrenNode.INTEGER_REGEXP_ = /^(0|[1-9]\d*)$/;
  class MaxNode extends ChildrenNode {
    constructor() {
      super(new SortedMap(NAME_COMPARATOR), ChildrenNode.EMPTY_NODE, IndexMap.Default);
    }
    compareTo(other) {
      if (other === this) {
        return 0;
      } else {
        return 1;
      }
    }
    equals(other) {
      return other === this;
    }
    getPriority() {
      return this;
    }
    getImmediateChild(childName) {
      return ChildrenNode.EMPTY_NODE;
    }
    isEmpty() {
      return false;
    }
  }
  const MAX_NODE = new MaxNode();
  Object.defineProperties(NamedNode, {
    MIN: {
      value: new NamedNode(MIN_NAME, ChildrenNode.EMPTY_NODE)
    },
    MAX: {
      value: new NamedNode(MAX_NAME, MAX_NODE)
    }
  });
  KeyIndex.__EMPTY_NODE = ChildrenNode.EMPTY_NODE;
  LeafNode.__childrenNodeConstructor = ChildrenNode;
  setMaxNode$1(MAX_NODE);
  setMaxNode(MAX_NODE);
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const USE_HINZE = true;
  function nodeFromJSON(json, priority = null) {
    if (json === null) {
      return ChildrenNode.EMPTY_NODE;
    }
    if (typeof json === "object" && ".priority" in json) {
      priority = json[".priority"];
    }
    assert(priority === null || typeof priority === "string" || typeof priority === "number" || typeof priority === "object" && ".sv" in priority, "Invalid priority type found: " + typeof priority);
    if (typeof json === "object" && ".value" in json && json[".value"] !== null) {
      json = json[".value"];
    }
    if (typeof json !== "object" || ".sv" in json) {
      const jsonLeaf = json;
      return new LeafNode(jsonLeaf, nodeFromJSON(priority));
    }
    if (!(json instanceof Array) && USE_HINZE) {
      const children = [];
      let childrenHavePriority = false;
      const hinzeJsonObj = json;
      each(hinzeJsonObj, (key, child2) => {
        if (key.substring(0, 1) !== ".") {
          const childNode = nodeFromJSON(child2);
          if (!childNode.isEmpty()) {
            childrenHavePriority = childrenHavePriority || !childNode.getPriority().isEmpty();
            children.push(new NamedNode(key, childNode));
          }
        }
      });
      if (children.length === 0) {
        return ChildrenNode.EMPTY_NODE;
      }
      const childSet = buildChildSet(children, NAME_ONLY_COMPARATOR, (namedNode) => namedNode.name, NAME_COMPARATOR);
      if (childrenHavePriority) {
        const sortedChildSet = buildChildSet(children, PRIORITY_INDEX.getCompare());
        return new ChildrenNode(childSet, nodeFromJSON(priority), new IndexMap({ ".priority": sortedChildSet }, { ".priority": PRIORITY_INDEX }));
      } else {
        return new ChildrenNode(childSet, nodeFromJSON(priority), IndexMap.Default);
      }
    } else {
      let node = ChildrenNode.EMPTY_NODE;
      each(json, (key, childData) => {
        if (contains(json, key)) {
          if (key.substring(0, 1) !== ".") {
            const childNode = nodeFromJSON(childData);
            if (childNode.isLeafNode() || !childNode.isEmpty()) {
              node = node.updateImmediateChild(key, childNode);
            }
          }
        }
      });
      return node.updatePriority(nodeFromJSON(priority));
    }
  }
  setNodeFromJSON(nodeFromJSON);
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class PathIndex extends Index {
    constructor(indexPath_) {
      super();
      this.indexPath_ = indexPath_;
      assert(!pathIsEmpty(indexPath_) && pathGetFront(indexPath_) !== ".priority", "Can't create PathIndex with empty path or .priority key");
    }
    extractChild(snap) {
      return snap.getChild(this.indexPath_);
    }
    isDefinedOn(node) {
      return !node.getChild(this.indexPath_).isEmpty();
    }
    compare(a2, b2) {
      const aChild = this.extractChild(a2.node);
      const bChild = this.extractChild(b2.node);
      const indexCmp = aChild.compareTo(bChild);
      if (indexCmp === 0) {
        return nameCompare(a2.name, b2.name);
      } else {
        return indexCmp;
      }
    }
    makePost(indexValue, name2) {
      const valueNode = nodeFromJSON(indexValue);
      const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, valueNode);
      return new NamedNode(name2, node);
    }
    maxPost() {
      const node = ChildrenNode.EMPTY_NODE.updateChild(this.indexPath_, MAX_NODE);
      return new NamedNode(MAX_NAME, node);
    }
    toString() {
      return pathSlice(this.indexPath_, 0).join("/");
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class ValueIndex extends Index {
    compare(a2, b2) {
      const indexCmp = a2.node.compareTo(b2.node);
      if (indexCmp === 0) {
        return nameCompare(a2.name, b2.name);
      } else {
        return indexCmp;
      }
    }
    isDefinedOn(node) {
      return true;
    }
    indexedValueChanged(oldNode, newNode) {
      return !oldNode.equals(newNode);
    }
    minPost() {
      return NamedNode.MIN;
    }
    maxPost() {
      return NamedNode.MAX;
    }
    makePost(indexValue, name2) {
      const valueNode = nodeFromJSON(indexValue);
      return new NamedNode(name2, valueNode);
    }
    /**
     * @returns String representation for inclusion in a query spec
     */
    toString() {
      return ".value";
    }
  }
  const VALUE_INDEX = new ValueIndex();
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function changeValue(snapshotNode) {
    return { type: "value", snapshotNode };
  }
  function changeChildAdded(childName, snapshotNode) {
    return { type: "child_added", snapshotNode, childName };
  }
  function changeChildRemoved(childName, snapshotNode) {
    return { type: "child_removed", snapshotNode, childName };
  }
  function changeChildChanged(childName, snapshotNode, oldSnap) {
    return {
      type: "child_changed",
      snapshotNode,
      childName,
      oldSnap
    };
  }
  function changeChildMoved(childName, snapshotNode) {
    return { type: "child_moved", snapshotNode, childName };
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class IndexedFilter {
    constructor(index_) {
      this.index_ = index_;
    }
    updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
      assert(snap.isIndexed(this.index_), "A node must be indexed if only a child is updated");
      const oldChild = snap.getImmediateChild(key);
      if (oldChild.getChild(affectedPath).equals(newChild.getChild(affectedPath))) {
        if (oldChild.isEmpty() === newChild.isEmpty()) {
          return snap;
        }
      }
      if (optChangeAccumulator != null) {
        if (newChild.isEmpty()) {
          if (snap.hasChild(key)) {
            optChangeAccumulator.trackChildChange(changeChildRemoved(key, oldChild));
          } else {
            assert(snap.isLeafNode(), "A child remove without an old child only makes sense on a leaf node");
          }
        } else if (oldChild.isEmpty()) {
          optChangeAccumulator.trackChildChange(changeChildAdded(key, newChild));
        } else {
          optChangeAccumulator.trackChildChange(changeChildChanged(key, newChild, oldChild));
        }
      }
      if (snap.isLeafNode() && newChild.isEmpty()) {
        return snap;
      } else {
        return snap.updateImmediateChild(key, newChild).withIndex(this.index_);
      }
    }
    updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
      if (optChangeAccumulator != null) {
        if (!oldSnap.isLeafNode()) {
          oldSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
            if (!newSnap.hasChild(key)) {
              optChangeAccumulator.trackChildChange(changeChildRemoved(key, childNode));
            }
          });
        }
        if (!newSnap.isLeafNode()) {
          newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
            if (oldSnap.hasChild(key)) {
              const oldChild = oldSnap.getImmediateChild(key);
              if (!oldChild.equals(childNode)) {
                optChangeAccumulator.trackChildChange(changeChildChanged(key, childNode, oldChild));
              }
            } else {
              optChangeAccumulator.trackChildChange(changeChildAdded(key, childNode));
            }
          });
        }
      }
      return newSnap.withIndex(this.index_);
    }
    updatePriority(oldSnap, newPriority) {
      if (oldSnap.isEmpty()) {
        return ChildrenNode.EMPTY_NODE;
      } else {
        return oldSnap.updatePriority(newPriority);
      }
    }
    filtersNodes() {
      return false;
    }
    getIndexedFilter() {
      return this;
    }
    getIndex() {
      return this.index_;
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class RangedFilter {
    constructor(params) {
      this.indexedFilter_ = new IndexedFilter(params.getIndex());
      this.index_ = params.getIndex();
      this.startPost_ = RangedFilter.getStartPost_(params);
      this.endPost_ = RangedFilter.getEndPost_(params);
      this.startIsInclusive_ = !params.startAfterSet_;
      this.endIsInclusive_ = !params.endBeforeSet_;
    }
    getStartPost() {
      return this.startPost_;
    }
    getEndPost() {
      return this.endPost_;
    }
    matches(node) {
      const isWithinStart = this.startIsInclusive_ ? this.index_.compare(this.getStartPost(), node) <= 0 : this.index_.compare(this.getStartPost(), node) < 0;
      const isWithinEnd = this.endIsInclusive_ ? this.index_.compare(node, this.getEndPost()) <= 0 : this.index_.compare(node, this.getEndPost()) < 0;
      return isWithinStart && isWithinEnd;
    }
    updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
      if (!this.matches(new NamedNode(key, newChild))) {
        newChild = ChildrenNode.EMPTY_NODE;
      }
      return this.indexedFilter_.updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
    }
    updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
      if (newSnap.isLeafNode()) {
        newSnap = ChildrenNode.EMPTY_NODE;
      }
      let filtered = newSnap.withIndex(this.index_);
      filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
      const self2 = this;
      newSnap.forEachChild(PRIORITY_INDEX, (key, childNode) => {
        if (!self2.matches(new NamedNode(key, childNode))) {
          filtered = filtered.updateImmediateChild(key, ChildrenNode.EMPTY_NODE);
        }
      });
      return this.indexedFilter_.updateFullNode(oldSnap, filtered, optChangeAccumulator);
    }
    updatePriority(oldSnap, newPriority) {
      return oldSnap;
    }
    filtersNodes() {
      return true;
    }
    getIndexedFilter() {
      return this.indexedFilter_;
    }
    getIndex() {
      return this.index_;
    }
    static getStartPost_(params) {
      if (params.hasStart()) {
        const startName = params.getIndexStartName();
        return params.getIndex().makePost(params.getIndexStartValue(), startName);
      } else {
        return params.getIndex().minPost();
      }
    }
    static getEndPost_(params) {
      if (params.hasEnd()) {
        const endName = params.getIndexEndName();
        return params.getIndex().makePost(params.getIndexEndValue(), endName);
      } else {
        return params.getIndex().maxPost();
      }
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class LimitedFilter {
    constructor(params) {
      this.withinDirectionalStart = (node) => this.reverse_ ? this.withinEndPost(node) : this.withinStartPost(node);
      this.withinDirectionalEnd = (node) => this.reverse_ ? this.withinStartPost(node) : this.withinEndPost(node);
      this.withinStartPost = (node) => {
        const compareRes = this.index_.compare(this.rangedFilter_.getStartPost(), node);
        return this.startIsInclusive_ ? compareRes <= 0 : compareRes < 0;
      };
      this.withinEndPost = (node) => {
        const compareRes = this.index_.compare(node, this.rangedFilter_.getEndPost());
        return this.endIsInclusive_ ? compareRes <= 0 : compareRes < 0;
      };
      this.rangedFilter_ = new RangedFilter(params);
      this.index_ = params.getIndex();
      this.limit_ = params.getLimit();
      this.reverse_ = !params.isViewFromLeft();
      this.startIsInclusive_ = !params.startAfterSet_;
      this.endIsInclusive_ = !params.endBeforeSet_;
    }
    updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator) {
      if (!this.rangedFilter_.matches(new NamedNode(key, newChild))) {
        newChild = ChildrenNode.EMPTY_NODE;
      }
      if (snap.getImmediateChild(key).equals(newChild)) {
        return snap;
      } else if (snap.numChildren() < this.limit_) {
        return this.rangedFilter_.getIndexedFilter().updateChild(snap, key, newChild, affectedPath, source, optChangeAccumulator);
      } else {
        return this.fullLimitUpdateChild_(snap, key, newChild, source, optChangeAccumulator);
      }
    }
    updateFullNode(oldSnap, newSnap, optChangeAccumulator) {
      let filtered;
      if (newSnap.isLeafNode() || newSnap.isEmpty()) {
        filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
      } else {
        if (this.limit_ * 2 < newSnap.numChildren() && newSnap.isIndexed(this.index_)) {
          filtered = ChildrenNode.EMPTY_NODE.withIndex(this.index_);
          let iterator;
          if (this.reverse_) {
            iterator = newSnap.getReverseIteratorFrom(this.rangedFilter_.getEndPost(), this.index_);
          } else {
            iterator = newSnap.getIteratorFrom(this.rangedFilter_.getStartPost(), this.index_);
          }
          let count = 0;
          while (iterator.hasNext() && count < this.limit_) {
            const next = iterator.getNext();
            if (!this.withinDirectionalStart(next)) {
              continue;
            } else if (!this.withinDirectionalEnd(next)) {
              break;
            } else {
              filtered = filtered.updateImmediateChild(next.name, next.node);
              count++;
            }
          }
        } else {
          filtered = newSnap.withIndex(this.index_);
          filtered = filtered.updatePriority(ChildrenNode.EMPTY_NODE);
          let iterator;
          if (this.reverse_) {
            iterator = filtered.getReverseIterator(this.index_);
          } else {
            iterator = filtered.getIterator(this.index_);
          }
          let count = 0;
          while (iterator.hasNext()) {
            const next = iterator.getNext();
            const inRange = count < this.limit_ && this.withinDirectionalStart(next) && this.withinDirectionalEnd(next);
            if (inRange) {
              count++;
            } else {
              filtered = filtered.updateImmediateChild(next.name, ChildrenNode.EMPTY_NODE);
            }
          }
        }
      }
      return this.rangedFilter_.getIndexedFilter().updateFullNode(oldSnap, filtered, optChangeAccumulator);
    }
    updatePriority(oldSnap, newPriority) {
      return oldSnap;
    }
    filtersNodes() {
      return true;
    }
    getIndexedFilter() {
      return this.rangedFilter_.getIndexedFilter();
    }
    getIndex() {
      return this.index_;
    }
    fullLimitUpdateChild_(snap, childKey, childSnap, source, changeAccumulator) {
      let cmp;
      if (this.reverse_) {
        const indexCmp = this.index_.getCompare();
        cmp = (a2, b2) => indexCmp(b2, a2);
      } else {
        cmp = this.index_.getCompare();
      }
      const oldEventCache = snap;
      assert(oldEventCache.numChildren() === this.limit_, "");
      const newChildNamedNode = new NamedNode(childKey, childSnap);
      const windowBoundary = this.reverse_ ? oldEventCache.getFirstChild(this.index_) : oldEventCache.getLastChild(this.index_);
      const inRange = this.rangedFilter_.matches(newChildNamedNode);
      if (oldEventCache.hasChild(childKey)) {
        const oldChildSnap = oldEventCache.getImmediateChild(childKey);
        let nextChild = source.getChildAfterChild(this.index_, windowBoundary, this.reverse_);
        while (nextChild != null && (nextChild.name === childKey || oldEventCache.hasChild(nextChild.name))) {
          nextChild = source.getChildAfterChild(this.index_, nextChild, this.reverse_);
        }
        const compareNext = nextChild == null ? 1 : cmp(nextChild, newChildNamedNode);
        const remainsInWindow = inRange && !childSnap.isEmpty() && compareNext >= 0;
        if (remainsInWindow) {
          if (changeAccumulator != null) {
            changeAccumulator.trackChildChange(changeChildChanged(childKey, childSnap, oldChildSnap));
          }
          return oldEventCache.updateImmediateChild(childKey, childSnap);
        } else {
          if (changeAccumulator != null) {
            changeAccumulator.trackChildChange(changeChildRemoved(childKey, oldChildSnap));
          }
          const newEventCache = oldEventCache.updateImmediateChild(childKey, ChildrenNode.EMPTY_NODE);
          const nextChildInRange = nextChild != null && this.rangedFilter_.matches(nextChild);
          if (nextChildInRange) {
            if (changeAccumulator != null) {
              changeAccumulator.trackChildChange(changeChildAdded(nextChild.name, nextChild.node));
            }
            return newEventCache.updateImmediateChild(nextChild.name, nextChild.node);
          } else {
            return newEventCache;
          }
        }
      } else if (childSnap.isEmpty()) {
        return snap;
      } else if (inRange) {
        if (cmp(windowBoundary, newChildNamedNode) >= 0) {
          if (changeAccumulator != null) {
            changeAccumulator.trackChildChange(changeChildRemoved(windowBoundary.name, windowBoundary.node));
            changeAccumulator.trackChildChange(changeChildAdded(childKey, childSnap));
          }
          return oldEventCache.updateImmediateChild(childKey, childSnap).updateImmediateChild(windowBoundary.name, ChildrenNode.EMPTY_NODE);
        } else {
          return snap;
        }
      } else {
        return snap;
      }
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class QueryParams {
    constructor() {
      this.limitSet_ = false;
      this.startSet_ = false;
      this.startNameSet_ = false;
      this.startAfterSet_ = false;
      this.endSet_ = false;
      this.endNameSet_ = false;
      this.endBeforeSet_ = false;
      this.limit_ = 0;
      this.viewFrom_ = "";
      this.indexStartValue_ = null;
      this.indexStartName_ = "";
      this.indexEndValue_ = null;
      this.indexEndName_ = "";
      this.index_ = PRIORITY_INDEX;
    }
    hasStart() {
      return this.startSet_;
    }
    /**
     * @returns True if it would return from left.
     */
    isViewFromLeft() {
      if (this.viewFrom_ === "") {
        return this.startSet_;
      } else {
        return this.viewFrom_ === "l";
      }
    }
    /**
     * Only valid to call if hasStart() returns true
     */
    getIndexStartValue() {
      assert(this.startSet_, "Only valid if start has been set");
      return this.indexStartValue_;
    }
    /**
     * Only valid to call if hasStart() returns true.
     * Returns the starting key name for the range defined by these query parameters
     */
    getIndexStartName() {
      assert(this.startSet_, "Only valid if start has been set");
      if (this.startNameSet_) {
        return this.indexStartName_;
      } else {
        return MIN_NAME;
      }
    }
    hasEnd() {
      return this.endSet_;
    }
    /**
     * Only valid to call if hasEnd() returns true.
     */
    getIndexEndValue() {
      assert(this.endSet_, "Only valid if end has been set");
      return this.indexEndValue_;
    }
    /**
     * Only valid to call if hasEnd() returns true.
     * Returns the end key name for the range defined by these query parameters
     */
    getIndexEndName() {
      assert(this.endSet_, "Only valid if end has been set");
      if (this.endNameSet_) {
        return this.indexEndName_;
      } else {
        return MAX_NAME;
      }
    }
    hasLimit() {
      return this.limitSet_;
    }
    /**
     * @returns True if a limit has been set and it has been explicitly anchored
     */
    hasAnchoredLimit() {
      return this.limitSet_ && this.viewFrom_ !== "";
    }
    /**
     * Only valid to call if hasLimit() returns true
     */
    getLimit() {
      assert(this.limitSet_, "Only valid if limit has been set");
      return this.limit_;
    }
    getIndex() {
      return this.index_;
    }
    loadsAllData() {
      return !(this.startSet_ || this.endSet_ || this.limitSet_);
    }
    isDefault() {
      return this.loadsAllData() && this.index_ === PRIORITY_INDEX;
    }
    copy() {
      const copy2 = new QueryParams();
      copy2.limitSet_ = this.limitSet_;
      copy2.limit_ = this.limit_;
      copy2.startSet_ = this.startSet_;
      copy2.startAfterSet_ = this.startAfterSet_;
      copy2.indexStartValue_ = this.indexStartValue_;
      copy2.startNameSet_ = this.startNameSet_;
      copy2.indexStartName_ = this.indexStartName_;
      copy2.endSet_ = this.endSet_;
      copy2.endBeforeSet_ = this.endBeforeSet_;
      copy2.indexEndValue_ = this.indexEndValue_;
      copy2.endNameSet_ = this.endNameSet_;
      copy2.indexEndName_ = this.indexEndName_;
      copy2.index_ = this.index_;
      copy2.viewFrom_ = this.viewFrom_;
      return copy2;
    }
  }
  function queryParamsGetNodeFilter(queryParams) {
    if (queryParams.loadsAllData()) {
      return new IndexedFilter(queryParams.getIndex());
    } else if (queryParams.hasLimit()) {
      return new LimitedFilter(queryParams);
    } else {
      return new RangedFilter(queryParams);
    }
  }
  function queryParamsToRestQueryStringParameters(queryParams) {
    const qs = {};
    if (queryParams.isDefault()) {
      return qs;
    }
    let orderBy;
    if (queryParams.index_ === PRIORITY_INDEX) {
      orderBy = "$priority";
    } else if (queryParams.index_ === VALUE_INDEX) {
      orderBy = "$value";
    } else if (queryParams.index_ === KEY_INDEX) {
      orderBy = "$key";
    } else {
      assert(queryParams.index_ instanceof PathIndex, "Unrecognized index type!");
      orderBy = queryParams.index_.toString();
    }
    qs[
      "orderBy"
      /* REST_QUERY_CONSTANTS.ORDER_BY */
    ] = stringify(orderBy);
    if (queryParams.startSet_) {
      const startParam = queryParams.startAfterSet_ ? "startAfter" : "startAt";
      qs[startParam] = stringify(queryParams.indexStartValue_);
      if (queryParams.startNameSet_) {
        qs[startParam] += "," + stringify(queryParams.indexStartName_);
      }
    }
    if (queryParams.endSet_) {
      const endParam = queryParams.endBeforeSet_ ? "endBefore" : "endAt";
      qs[endParam] = stringify(queryParams.indexEndValue_);
      if (queryParams.endNameSet_) {
        qs[endParam] += "," + stringify(queryParams.indexEndName_);
      }
    }
    if (queryParams.limitSet_) {
      if (queryParams.isViewFromLeft()) {
        qs[
          "limitToFirst"
          /* REST_QUERY_CONSTANTS.LIMIT_TO_FIRST */
        ] = queryParams.limit_;
      } else {
        qs[
          "limitToLast"
          /* REST_QUERY_CONSTANTS.LIMIT_TO_LAST */
        ] = queryParams.limit_;
      }
    }
    return qs;
  }
  function queryParamsGetQueryObject(queryParams) {
    const obj = {};
    if (queryParams.startSet_) {
      obj[
        "sp"
        /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_VALUE */
      ] = queryParams.indexStartValue_;
      if (queryParams.startNameSet_) {
        obj[
          "sn"
          /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_NAME */
        ] = queryParams.indexStartName_;
      }
      obj[
        "sin"
        /* WIRE_PROTOCOL_CONSTANTS.INDEX_START_IS_INCLUSIVE */
      ] = !queryParams.startAfterSet_;
    }
    if (queryParams.endSet_) {
      obj[
        "ep"
        /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_VALUE */
      ] = queryParams.indexEndValue_;
      if (queryParams.endNameSet_) {
        obj[
          "en"
          /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_NAME */
        ] = queryParams.indexEndName_;
      }
      obj[
        "ein"
        /* WIRE_PROTOCOL_CONSTANTS.INDEX_END_IS_INCLUSIVE */
      ] = !queryParams.endBeforeSet_;
    }
    if (queryParams.limitSet_) {
      obj[
        "l"
        /* WIRE_PROTOCOL_CONSTANTS.LIMIT */
      ] = queryParams.limit_;
      let viewFrom = queryParams.viewFrom_;
      if (viewFrom === "") {
        if (queryParams.isViewFromLeft()) {
          viewFrom = "l";
        } else {
          viewFrom = "r";
        }
      }
      obj[
        "vf"
        /* WIRE_PROTOCOL_CONSTANTS.VIEW_FROM */
      ] = viewFrom;
    }
    if (queryParams.index_ !== PRIORITY_INDEX) {
      obj[
        "i"
        /* WIRE_PROTOCOL_CONSTANTS.INDEX */
      ] = queryParams.index_.toString();
    }
    return obj;
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class ReadonlyRestClient extends ServerActions {
    /**
     * @param repoInfo_ - Data about the namespace we are connecting to
     * @param onDataUpdate_ - A callback for new data from the server
     */
    constructor(repoInfo_, onDataUpdate_, authTokenProvider_, appCheckTokenProvider_) {
      super();
      this.repoInfo_ = repoInfo_;
      this.onDataUpdate_ = onDataUpdate_;
      this.authTokenProvider_ = authTokenProvider_;
      this.appCheckTokenProvider_ = appCheckTokenProvider_;
      this.log_ = logWrapper("p:rest:");
      this.listens_ = {};
    }
    reportStats(stats) {
      throw new Error("Method not implemented.");
    }
    static getListenId_(query, tag) {
      if (tag !== void 0) {
        return "tag$" + tag;
      } else {
        assert(query._queryParams.isDefault(), "should have a tag if it's not a default query.");
        return query._path.toString();
      }
    }
    /** @inheritDoc */
    listen(query, currentHashFn, tag, onComplete) {
      const pathString = query._path.toString();
      this.log_("Listen called for " + pathString + " " + query._queryIdentifier);
      const listenId = ReadonlyRestClient.getListenId_(query, tag);
      const thisListen = {};
      this.listens_[listenId] = thisListen;
      const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
      this.restRequest_(pathString + ".json", queryStringParameters, (error2, result) => {
        let data = result;
        if (error2 === 404) {
          data = null;
          error2 = null;
        }
        if (error2 === null) {
          this.onDataUpdate_(
            pathString,
            data,
            /*isMerge=*/
            false,
            tag
          );
        }
        if (safeGet(this.listens_, listenId) === thisListen) {
          let status;
          if (!error2) {
            status = "ok";
          } else if (error2 === 401) {
            status = "permission_denied";
          } else {
            status = "rest_error:" + error2;
          }
          onComplete(status, null);
        }
      });
    }
    /** @inheritDoc */
    unlisten(query, tag) {
      const listenId = ReadonlyRestClient.getListenId_(query, tag);
      delete this.listens_[listenId];
    }
    get(query) {
      const queryStringParameters = queryParamsToRestQueryStringParameters(query._queryParams);
      const pathString = query._path.toString();
      const deferred = new Deferred();
      this.restRequest_(pathString + ".json", queryStringParameters, (error2, result) => {
        let data = result;
        if (error2 === 404) {
          data = null;
          error2 = null;
        }
        if (error2 === null) {
          this.onDataUpdate_(
            pathString,
            data,
            /*isMerge=*/
            false,
            /*tag=*/
            null
          );
          deferred.resolve(data);
        } else {
          deferred.reject(new Error(data));
        }
      });
      return deferred.promise;
    }
    /** @inheritDoc */
    refreshAuthToken(token) {
    }
    /**
     * Performs a REST request to the given path, with the provided query string parameters,
     * and any auth credentials we have.
     */
    restRequest_(pathString, queryStringParameters = {}, callback) {
      queryStringParameters["format"] = "export";
      return Promise.all([
        this.authTokenProvider_.getToken(
          /*forceRefresh=*/
          false
        ),
        this.appCheckTokenProvider_.getToken(
          /*forceRefresh=*/
          false
        )
      ]).then(([authToken, appCheckToken]) => {
        if (authToken && authToken.accessToken) {
          queryStringParameters["auth"] = authToken.accessToken;
        }
        if (appCheckToken && appCheckToken.token) {
          queryStringParameters["ac"] = appCheckToken.token;
        }
        const url = (this.repoInfo_.secure ? "https://" : "http://") + this.repoInfo_.host + pathString + "?ns=" + this.repoInfo_.namespace + querystring(queryStringParameters);
        this.log_("Sending REST request for " + url);
        const xhr = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
          if (callback && xhr.readyState === 4) {
            this.log_("REST Response for " + url + " received. status:", xhr.status, "response:", xhr.responseText);
            let res = null;
            if (xhr.status >= 200 && xhr.status < 300) {
              try {
                res = jsonEval(xhr.responseText);
              } catch (e2) {
                warn("Failed to parse JSON response for " + url + ": " + xhr.responseText);
              }
              callback(null, res);
            } else {
              if (xhr.status !== 401 && xhr.status !== 404) {
                warn("Got unsuccessful REST response for " + url + " Status: " + xhr.status);
              }
              callback(xhr.status);
            }
            callback = null;
          }
        };
        xhr.open(
          "GET",
          url,
          /*asynchronous=*/
          true
        );
        xhr.send();
      });
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class SnapshotHolder {
    constructor() {
      this.rootNode_ = ChildrenNode.EMPTY_NODE;
    }
    getNode(path) {
      return this.rootNode_.getChild(path);
    }
    updateSnapshot(path, newSnapshotNode) {
      this.rootNode_ = this.rootNode_.updateChild(path, newSnapshotNode);
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function newSparseSnapshotTree() {
    return {
      value: null,
      children: /* @__PURE__ */ new Map()
    };
  }
  function sparseSnapshotTreeRemember(sparseSnapshotTree, path, data) {
    if (pathIsEmpty(path)) {
      sparseSnapshotTree.value = data;
      sparseSnapshotTree.children.clear();
    } else if (sparseSnapshotTree.value !== null) {
      sparseSnapshotTree.value = sparseSnapshotTree.value.updateChild(path, data);
    } else {
      const childKey = pathGetFront(path);
      if (!sparseSnapshotTree.children.has(childKey)) {
        sparseSnapshotTree.children.set(childKey, newSparseSnapshotTree());
      }
      const child2 = sparseSnapshotTree.children.get(childKey);
      path = pathPopFront(path);
      sparseSnapshotTreeRemember(child2, path, data);
    }
  }
  function sparseSnapshotTreeForEachTree(sparseSnapshotTree, prefixPath, func) {
    if (sparseSnapshotTree.value !== null) {
      func(prefixPath, sparseSnapshotTree.value);
    } else {
      sparseSnapshotTreeForEachChild(sparseSnapshotTree, (key, tree) => {
        const path = new Path(prefixPath.toString() + "/" + key);
        sparseSnapshotTreeForEachTree(tree, path, func);
      });
    }
  }
  function sparseSnapshotTreeForEachChild(sparseSnapshotTree, func) {
    sparseSnapshotTree.children.forEach((tree, key) => {
      func(key, tree);
    });
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class StatsListener {
    constructor(collection_) {
      this.collection_ = collection_;
      this.last_ = null;
    }
    get() {
      const newStats = this.collection_.get();
      const delta = Object.assign({}, newStats);
      if (this.last_) {
        each(this.last_, (stat, value) => {
          delta[stat] = delta[stat] - value;
        });
      }
      this.last_ = newStats;
      return delta;
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const FIRST_STATS_MIN_TIME = 10 * 1e3;
  const FIRST_STATS_MAX_TIME = 30 * 1e3;
  const REPORT_STATS_INTERVAL = 5 * 60 * 1e3;
  class StatsReporter {
    constructor(collection, server_) {
      this.server_ = server_;
      this.statsToReport_ = {};
      this.statsListener_ = new StatsListener(collection);
      const timeout = FIRST_STATS_MIN_TIME + (FIRST_STATS_MAX_TIME - FIRST_STATS_MIN_TIME) * Math.random();
      setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(timeout));
    }
    reportStats_() {
      const stats = this.statsListener_.get();
      const reportedStats = {};
      let haveStatsToReport = false;
      each(stats, (stat, value) => {
        if (value > 0 && contains(this.statsToReport_, stat)) {
          reportedStats[stat] = value;
          haveStatsToReport = true;
        }
      });
      if (haveStatsToReport) {
        this.server_.reportStats(reportedStats);
      }
      setTimeoutNonBlocking(this.reportStats_.bind(this), Math.floor(Math.random() * 2 * REPORT_STATS_INTERVAL));
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  var OperationType;
  (function(OperationType2) {
    OperationType2[OperationType2["OVERWRITE"] = 0] = "OVERWRITE";
    OperationType2[OperationType2["MERGE"] = 1] = "MERGE";
    OperationType2[OperationType2["ACK_USER_WRITE"] = 2] = "ACK_USER_WRITE";
    OperationType2[OperationType2["LISTEN_COMPLETE"] = 3] = "LISTEN_COMPLETE";
  })(OperationType || (OperationType = {}));
  function newOperationSourceUser() {
    return {
      fromUser: true,
      fromServer: false,
      queryId: null,
      tagged: false
    };
  }
  function newOperationSourceServer() {
    return {
      fromUser: false,
      fromServer: true,
      queryId: null,
      tagged: false
    };
  }
  function newOperationSourceServerTaggedQuery(queryId) {
    return {
      fromUser: false,
      fromServer: true,
      queryId,
      tagged: true
    };
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class AckUserWrite {
    /**
     * @param affectedTree - A tree containing true for each affected path. Affected paths can't overlap.
     */
    constructor(path, affectedTree, revert) {
      this.path = path;
      this.affectedTree = affectedTree;
      this.revert = revert;
      this.type = OperationType.ACK_USER_WRITE;
      this.source = newOperationSourceUser();
    }
    operationForChild(childName) {
      if (!pathIsEmpty(this.path)) {
        assert(pathGetFront(this.path) === childName, "operationForChild called for unrelated child.");
        return new AckUserWrite(pathPopFront(this.path), this.affectedTree, this.revert);
      } else if (this.affectedTree.value != null) {
        assert(this.affectedTree.children.isEmpty(), "affectedTree should not have overlapping affected paths.");
        return this;
      } else {
        const childTree = this.affectedTree.subtree(new Path(childName));
        return new AckUserWrite(newEmptyPath(), childTree, this.revert);
      }
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class ListenComplete {
    constructor(source, path) {
      this.source = source;
      this.path = path;
      this.type = OperationType.LISTEN_COMPLETE;
    }
    operationForChild(childName) {
      if (pathIsEmpty(this.path)) {
        return new ListenComplete(this.source, newEmptyPath());
      } else {
        return new ListenComplete(this.source, pathPopFront(this.path));
      }
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class Overwrite {
    constructor(source, path, snap) {
      this.source = source;
      this.path = path;
      this.snap = snap;
      this.type = OperationType.OVERWRITE;
    }
    operationForChild(childName) {
      if (pathIsEmpty(this.path)) {
        return new Overwrite(this.source, newEmptyPath(), this.snap.getImmediateChild(childName));
      } else {
        return new Overwrite(this.source, pathPopFront(this.path), this.snap);
      }
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class Merge {
    constructor(source, path, children) {
      this.source = source;
      this.path = path;
      this.children = children;
      this.type = OperationType.MERGE;
    }
    operationForChild(childName) {
      if (pathIsEmpty(this.path)) {
        const childTree = this.children.subtree(new Path(childName));
        if (childTree.isEmpty()) {
          return null;
        } else if (childTree.value) {
          return new Overwrite(this.source, newEmptyPath(), childTree.value);
        } else {
          return new Merge(this.source, newEmptyPath(), childTree);
        }
      } else {
        assert(pathGetFront(this.path) === childName, "Can't get a merge for a child not on the path of the operation");
        return new Merge(this.source, pathPopFront(this.path), this.children);
      }
    }
    toString() {
      return "Operation(" + this.path + ": " + this.source.toString() + " merge: " + this.children.toString() + ")";
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class CacheNode {
    constructor(node_, fullyInitialized_, filtered_) {
      this.node_ = node_;
      this.fullyInitialized_ = fullyInitialized_;
      this.filtered_ = filtered_;
    }
    /**
     * Returns whether this node was fully initialized with either server data or a complete overwrite by the client
     */
    isFullyInitialized() {
      return this.fullyInitialized_;
    }
    /**
     * Returns whether this node is potentially missing children due to a filter applied to the node
     */
    isFiltered() {
      return this.filtered_;
    }
    isCompleteForPath(path) {
      if (pathIsEmpty(path)) {
        return this.isFullyInitialized() && !this.filtered_;
      }
      const childKey = pathGetFront(path);
      return this.isCompleteForChild(childKey);
    }
    isCompleteForChild(key) {
      return this.isFullyInitialized() && !this.filtered_ || this.node_.hasChild(key);
    }
    getNode() {
      return this.node_;
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class EventGenerator {
    constructor(query_) {
      this.query_ = query_;
      this.index_ = this.query_._queryParams.getIndex();
    }
  }
  function eventGeneratorGenerateEventsForChanges(eventGenerator, changes, eventCache, eventRegistrations) {
    const events2 = [];
    const moves = [];
    changes.forEach((change) => {
      if (change.type === "child_changed" && eventGenerator.index_.indexedValueChanged(change.oldSnap, change.snapshotNode)) {
        moves.push(changeChildMoved(change.childName, change.snapshotNode));
      }
    });
    eventGeneratorGenerateEventsForType(eventGenerator, events2, "child_removed", changes, eventRegistrations, eventCache);
    eventGeneratorGenerateEventsForType(eventGenerator, events2, "child_added", changes, eventRegistrations, eventCache);
    eventGeneratorGenerateEventsForType(eventGenerator, events2, "child_moved", moves, eventRegistrations, eventCache);
    eventGeneratorGenerateEventsForType(eventGenerator, events2, "child_changed", changes, eventRegistrations, eventCache);
    eventGeneratorGenerateEventsForType(eventGenerator, events2, "value", changes, eventRegistrations, eventCache);
    return events2;
  }
  function eventGeneratorGenerateEventsForType(eventGenerator, events2, eventType, changes, registrations, eventCache) {
    const filteredChanges = changes.filter((change) => change.type === eventType);
    filteredChanges.sort((a2, b2) => eventGeneratorCompareChanges(eventGenerator, a2, b2));
    filteredChanges.forEach((change) => {
      const materializedChange = eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache);
      registrations.forEach((registration) => {
        if (registration.respondsTo(change.type)) {
          events2.push(registration.createEvent(materializedChange, eventGenerator.query_));
        }
      });
    });
  }
  function eventGeneratorMaterializeSingleChange(eventGenerator, change, eventCache) {
    if (change.type === "value" || change.type === "child_removed") {
      return change;
    } else {
      change.prevName = eventCache.getPredecessorChildName(change.childName, change.snapshotNode, eventGenerator.index_);
      return change;
    }
  }
  function eventGeneratorCompareChanges(eventGenerator, a2, b2) {
    if (a2.childName == null || b2.childName == null) {
      throw assertionError("Should only compare child_ events.");
    }
    const aWrapped = new NamedNode(a2.childName, a2.snapshotNode);
    const bWrapped = new NamedNode(b2.childName, b2.snapshotNode);
    return eventGenerator.index_.compare(aWrapped, bWrapped);
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function newViewCache(eventCache, serverCache) {
    return { eventCache, serverCache };
  }
  function viewCacheUpdateEventSnap(viewCache, eventSnap, complete, filtered) {
    return newViewCache(new CacheNode(eventSnap, complete, filtered), viewCache.serverCache);
  }
  function viewCacheUpdateServerSnap(viewCache, serverSnap, complete, filtered) {
    return newViewCache(viewCache.eventCache, new CacheNode(serverSnap, complete, filtered));
  }
  function viewCacheGetCompleteEventSnap(viewCache) {
    return viewCache.eventCache.isFullyInitialized() ? viewCache.eventCache.getNode() : null;
  }
  function viewCacheGetCompleteServerSnap(viewCache) {
    return viewCache.serverCache.isFullyInitialized() ? viewCache.serverCache.getNode() : null;
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  let emptyChildrenSingleton;
  const EmptyChildren = () => {
    if (!emptyChildrenSingleton) {
      emptyChildrenSingleton = new SortedMap(stringCompare);
    }
    return emptyChildrenSingleton;
  };
  class ImmutableTree {
    constructor(value, children = EmptyChildren()) {
      this.value = value;
      this.children = children;
    }
    static fromObject(obj) {
      let tree = new ImmutableTree(null);
      each(obj, (childPath, childSnap) => {
        tree = tree.set(new Path(childPath), childSnap);
      });
      return tree;
    }
    /**
     * True if the value is empty and there are no children
     */
    isEmpty() {
      return this.value === null && this.children.isEmpty();
    }
    /**
     * Given a path and predicate, return the first node and the path to that node
     * where the predicate returns true.
     *
     * TODO Do a perf test -- If we're creating a bunch of `{path: value:}`
     * objects on the way back out, it may be better to pass down a pathSoFar obj.
     *
     * @param relativePath - The remainder of the path
     * @param predicate - The predicate to satisfy to return a node
     */
    findRootMostMatchingPathAndValue(relativePath, predicate) {
      if (this.value != null && predicate(this.value)) {
        return { path: newEmptyPath(), value: this.value };
      } else {
        if (pathIsEmpty(relativePath)) {
          return null;
        } else {
          const front = pathGetFront(relativePath);
          const child2 = this.children.get(front);
          if (child2 !== null) {
            const childExistingPathAndValue = child2.findRootMostMatchingPathAndValue(pathPopFront(relativePath), predicate);
            if (childExistingPathAndValue != null) {
              const fullPath = pathChild(new Path(front), childExistingPathAndValue.path);
              return { path: fullPath, value: childExistingPathAndValue.value };
            } else {
              return null;
            }
          } else {
            return null;
          }
        }
      }
    }
    /**
     * Find, if it exists, the shortest subpath of the given path that points a defined
     * value in the tree
     */
    findRootMostValueAndPath(relativePath) {
      return this.findRootMostMatchingPathAndValue(relativePath, () => true);
    }
    /**
     * @returns The subtree at the given path
     */
    subtree(relativePath) {
      if (pathIsEmpty(relativePath)) {
        return this;
      } else {
        const front = pathGetFront(relativePath);
        const childTree = this.children.get(front);
        if (childTree !== null) {
          return childTree.subtree(pathPopFront(relativePath));
        } else {
          return new ImmutableTree(null);
        }
      }
    }
    /**
     * Sets a value at the specified path.
     *
     * @param relativePath - Path to set value at.
     * @param toSet - Value to set.
     * @returns Resulting tree.
     */
    set(relativePath, toSet) {
      if (pathIsEmpty(relativePath)) {
        return new ImmutableTree(toSet, this.children);
      } else {
        const front = pathGetFront(relativePath);
        const child2 = this.children.get(front) || new ImmutableTree(null);
        const newChild = child2.set(pathPopFront(relativePath), toSet);
        const newChildren = this.children.insert(front, newChild);
        return new ImmutableTree(this.value, newChildren);
      }
    }
    /**
     * Removes the value at the specified path.
     *
     * @param relativePath - Path to value to remove.
     * @returns Resulting tree.
     */
    remove(relativePath) {
      if (pathIsEmpty(relativePath)) {
        if (this.children.isEmpty()) {
          return new ImmutableTree(null);
        } else {
          return new ImmutableTree(null, this.children);
        }
      } else {
        const front = pathGetFront(relativePath);
        const child2 = this.children.get(front);
        if (child2) {
          const newChild = child2.remove(pathPopFront(relativePath));
          let newChildren;
          if (newChild.isEmpty()) {
            newChildren = this.children.remove(front);
          } else {
            newChildren = this.children.insert(front, newChild);
          }
          if (this.value === null && newChildren.isEmpty()) {
            return new ImmutableTree(null);
          } else {
            return new ImmutableTree(this.value, newChildren);
          }
        } else {
          return this;
        }
      }
    }
    /**
     * Gets a value from the tree.
     *
     * @param relativePath - Path to get value for.
     * @returns Value at path, or null.
     */
    get(relativePath) {
      if (pathIsEmpty(relativePath)) {
        return this.value;
      } else {
        const front = pathGetFront(relativePath);
        const child2 = this.children.get(front);
        if (child2) {
          return child2.get(pathPopFront(relativePath));
        } else {
          return null;
        }
      }
    }
    /**
     * Replace the subtree at the specified path with the given new tree.
     *
     * @param relativePath - Path to replace subtree for.
     * @param newTree - New tree.
     * @returns Resulting tree.
     */
    setTree(relativePath, newTree) {
      if (pathIsEmpty(relativePath)) {
        return newTree;
      } else {
        const front = pathGetFront(relativePath);
        const child2 = this.children.get(front) || new ImmutableTree(null);
        const newChild = child2.setTree(pathPopFront(relativePath), newTree);
        let newChildren;
        if (newChild.isEmpty()) {
          newChildren = this.children.remove(front);
        } else {
          newChildren = this.children.insert(front, newChild);
        }
        return new ImmutableTree(this.value, newChildren);
      }
    }
    /**
     * Performs a depth first fold on this tree. Transforms a tree into a single
     * value, given a function that operates on the path to a node, an optional
     * current value, and a map of child names to folded subtrees
     */
    fold(fn2) {
      return this.fold_(newEmptyPath(), fn2);
    }
    /**
     * Recursive helper for public-facing fold() method
     */
    fold_(pathSoFar, fn2) {
      const accum = {};
      this.children.inorderTraversal((childKey, childTree) => {
        accum[childKey] = childTree.fold_(pathChild(pathSoFar, childKey), fn2);
      });
      return fn2(pathSoFar, this.value, accum);
    }
    /**
     * Find the first matching value on the given path. Return the result of applying f to it.
     */
    findOnPath(path, f2) {
      return this.findOnPath_(path, newEmptyPath(), f2);
    }
    findOnPath_(pathToFollow, pathSoFar, f2) {
      const result = this.value ? f2(pathSoFar, this.value) : false;
      if (result) {
        return result;
      } else {
        if (pathIsEmpty(pathToFollow)) {
          return null;
        } else {
          const front = pathGetFront(pathToFollow);
          const nextChild = this.children.get(front);
          if (nextChild) {
            return nextChild.findOnPath_(pathPopFront(pathToFollow), pathChild(pathSoFar, front), f2);
          } else {
            return null;
          }
        }
      }
    }
    foreachOnPath(path, f2) {
      return this.foreachOnPath_(path, newEmptyPath(), f2);
    }
    foreachOnPath_(pathToFollow, currentRelativePath, f2) {
      if (pathIsEmpty(pathToFollow)) {
        return this;
      } else {
        if (this.value) {
          f2(currentRelativePath, this.value);
        }
        const front = pathGetFront(pathToFollow);
        const nextChild = this.children.get(front);
        if (nextChild) {
          return nextChild.foreachOnPath_(pathPopFront(pathToFollow), pathChild(currentRelativePath, front), f2);
        } else {
          return new ImmutableTree(null);
        }
      }
    }
    /**
     * Calls the given function for each node in the tree that has a value.
     *
     * @param f - A function to be called with the path from the root of the tree to
     * a node, and the value at that node. Called in depth-first order.
     */
    foreach(f2) {
      this.foreach_(newEmptyPath(), f2);
    }
    foreach_(currentRelativePath, f2) {
      this.children.inorderTraversal((childName, childTree) => {
        childTree.foreach_(pathChild(currentRelativePath, childName), f2);
      });
      if (this.value) {
        f2(currentRelativePath, this.value);
      }
    }
    foreachChild(f2) {
      this.children.inorderTraversal((childName, childTree) => {
        if (childTree.value) {
          f2(childName, childTree.value);
        }
      });
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class CompoundWrite {
    constructor(writeTree_) {
      this.writeTree_ = writeTree_;
    }
    static empty() {
      return new CompoundWrite(new ImmutableTree(null));
    }
  }
  function compoundWriteAddWrite(compoundWrite, path, node) {
    if (pathIsEmpty(path)) {
      return new CompoundWrite(new ImmutableTree(node));
    } else {
      const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
      if (rootmost != null) {
        const rootMostPath = rootmost.path;
        let value = rootmost.value;
        const relativePath = newRelativePath(rootMostPath, path);
        value = value.updateChild(relativePath, node);
        return new CompoundWrite(compoundWrite.writeTree_.set(rootMostPath, value));
      } else {
        const subtree = new ImmutableTree(node);
        const newWriteTree2 = compoundWrite.writeTree_.setTree(path, subtree);
        return new CompoundWrite(newWriteTree2);
      }
    }
  }
  function compoundWriteAddWrites(compoundWrite, path, updates) {
    let newWrite = compoundWrite;
    each(updates, (childKey, node) => {
      newWrite = compoundWriteAddWrite(newWrite, pathChild(path, childKey), node);
    });
    return newWrite;
  }
  function compoundWriteRemoveWrite(compoundWrite, path) {
    if (pathIsEmpty(path)) {
      return CompoundWrite.empty();
    } else {
      const newWriteTree2 = compoundWrite.writeTree_.setTree(path, new ImmutableTree(null));
      return new CompoundWrite(newWriteTree2);
    }
  }
  function compoundWriteHasCompleteWrite(compoundWrite, path) {
    return compoundWriteGetCompleteNode(compoundWrite, path) != null;
  }
  function compoundWriteGetCompleteNode(compoundWrite, path) {
    const rootmost = compoundWrite.writeTree_.findRootMostValueAndPath(path);
    if (rootmost != null) {
      return compoundWrite.writeTree_.get(rootmost.path).getChild(newRelativePath(rootmost.path, path));
    } else {
      return null;
    }
  }
  function compoundWriteGetCompleteChildren(compoundWrite) {
    const children = [];
    const node = compoundWrite.writeTree_.value;
    if (node != null) {
      if (!node.isLeafNode()) {
        node.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
          children.push(new NamedNode(childName, childNode));
        });
      }
    } else {
      compoundWrite.writeTree_.children.inorderTraversal((childName, childTree) => {
        if (childTree.value != null) {
          children.push(new NamedNode(childName, childTree.value));
        }
      });
    }
    return children;
  }
  function compoundWriteChildCompoundWrite(compoundWrite, path) {
    if (pathIsEmpty(path)) {
      return compoundWrite;
    } else {
      const shadowingNode = compoundWriteGetCompleteNode(compoundWrite, path);
      if (shadowingNode != null) {
        return new CompoundWrite(new ImmutableTree(shadowingNode));
      } else {
        return new CompoundWrite(compoundWrite.writeTree_.subtree(path));
      }
    }
  }
  function compoundWriteIsEmpty(compoundWrite) {
    return compoundWrite.writeTree_.isEmpty();
  }
  function compoundWriteApply(compoundWrite, node) {
    return applySubtreeWrite(newEmptyPath(), compoundWrite.writeTree_, node);
  }
  function applySubtreeWrite(relativePath, writeTree, node) {
    if (writeTree.value != null) {
      return node.updateChild(relativePath, writeTree.value);
    } else {
      let priorityWrite = null;
      writeTree.children.inorderTraversal((childKey, childTree) => {
        if (childKey === ".priority") {
          assert(childTree.value !== null, "Priority writes must always be leaf nodes");
          priorityWrite = childTree.value;
        } else {
          node = applySubtreeWrite(pathChild(relativePath, childKey), childTree, node);
        }
      });
      if (!node.getChild(relativePath).isEmpty() && priorityWrite !== null) {
        node = node.updateChild(pathChild(relativePath, ".priority"), priorityWrite);
      }
      return node;
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function writeTreeChildWrites(writeTree, path) {
    return newWriteTreeRef(path, writeTree);
  }
  function writeTreeAddOverwrite(writeTree, path, snap, writeId, visible) {
    assert(writeId > writeTree.lastWriteId, "Stacking an older write on top of newer ones");
    if (visible === void 0) {
      visible = true;
    }
    writeTree.allWrites.push({
      path,
      snap,
      writeId,
      visible
    });
    if (visible) {
      writeTree.visibleWrites = compoundWriteAddWrite(writeTree.visibleWrites, path, snap);
    }
    writeTree.lastWriteId = writeId;
  }
  function writeTreeGetWrite(writeTree, writeId) {
    for (let i2 = 0; i2 < writeTree.allWrites.length; i2++) {
      const record = writeTree.allWrites[i2];
      if (record.writeId === writeId) {
        return record;
      }
    }
    return null;
  }
  function writeTreeRemoveWrite(writeTree, writeId) {
    const idx = writeTree.allWrites.findIndex((s2) => {
      return s2.writeId === writeId;
    });
    assert(idx >= 0, "removeWrite called with nonexistent writeId.");
    const writeToRemove = writeTree.allWrites[idx];
    writeTree.allWrites.splice(idx, 1);
    let removedWriteWasVisible = writeToRemove.visible;
    let removedWriteOverlapsWithOtherWrites = false;
    let i2 = writeTree.allWrites.length - 1;
    while (removedWriteWasVisible && i2 >= 0) {
      const currentWrite = writeTree.allWrites[i2];
      if (currentWrite.visible) {
        if (i2 >= idx && writeTreeRecordContainsPath_(currentWrite, writeToRemove.path)) {
          removedWriteWasVisible = false;
        } else if (pathContains(writeToRemove.path, currentWrite.path)) {
          removedWriteOverlapsWithOtherWrites = true;
        }
      }
      i2--;
    }
    if (!removedWriteWasVisible) {
      return false;
    } else if (removedWriteOverlapsWithOtherWrites) {
      writeTreeResetTree_(writeTree);
      return true;
    } else {
      if (writeToRemove.snap) {
        writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, writeToRemove.path);
      } else {
        const children = writeToRemove.children;
        each(children, (childName) => {
          writeTree.visibleWrites = compoundWriteRemoveWrite(writeTree.visibleWrites, pathChild(writeToRemove.path, childName));
        });
      }
      return true;
    }
  }
  function writeTreeRecordContainsPath_(writeRecord, path) {
    if (writeRecord.snap) {
      return pathContains(writeRecord.path, path);
    } else {
      for (const childName in writeRecord.children) {
        if (writeRecord.children.hasOwnProperty(childName) && pathContains(pathChild(writeRecord.path, childName), path)) {
          return true;
        }
      }
      return false;
    }
  }
  function writeTreeResetTree_(writeTree) {
    writeTree.visibleWrites = writeTreeLayerTree_(writeTree.allWrites, writeTreeDefaultFilter_, newEmptyPath());
    if (writeTree.allWrites.length > 0) {
      writeTree.lastWriteId = writeTree.allWrites[writeTree.allWrites.length - 1].writeId;
    } else {
      writeTree.lastWriteId = -1;
    }
  }
  function writeTreeDefaultFilter_(write) {
    return write.visible;
  }
  function writeTreeLayerTree_(writes, filter, treeRoot) {
    let compoundWrite = CompoundWrite.empty();
    for (let i2 = 0; i2 < writes.length; ++i2) {
      const write = writes[i2];
      if (filter(write)) {
        const writePath = write.path;
        let relativePath;
        if (write.snap) {
          if (pathContains(treeRoot, writePath)) {
            relativePath = newRelativePath(treeRoot, writePath);
            compoundWrite = compoundWriteAddWrite(compoundWrite, relativePath, write.snap);
          } else if (pathContains(writePath, treeRoot)) {
            relativePath = newRelativePath(writePath, treeRoot);
            compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), write.snap.getChild(relativePath));
          } else
            ;
        } else if (write.children) {
          if (pathContains(treeRoot, writePath)) {
            relativePath = newRelativePath(treeRoot, writePath);
            compoundWrite = compoundWriteAddWrites(compoundWrite, relativePath, write.children);
          } else if (pathContains(writePath, treeRoot)) {
            relativePath = newRelativePath(writePath, treeRoot);
            if (pathIsEmpty(relativePath)) {
              compoundWrite = compoundWriteAddWrites(compoundWrite, newEmptyPath(), write.children);
            } else {
              const child2 = safeGet(write.children, pathGetFront(relativePath));
              if (child2) {
                const deepNode = child2.getChild(pathPopFront(relativePath));
                compoundWrite = compoundWriteAddWrite(compoundWrite, newEmptyPath(), deepNode);
              }
            }
          } else
            ;
        } else {
          throw assertionError("WriteRecord should have .snap or .children");
        }
      }
    }
    return compoundWrite;
  }
  function writeTreeCalcCompleteEventCache(writeTree, treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
    if (!writeIdsToExclude && !includeHiddenWrites) {
      const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
      if (shadowingNode != null) {
        return shadowingNode;
      } else {
        const subMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
        if (compoundWriteIsEmpty(subMerge)) {
          return completeServerCache;
        } else if (completeServerCache == null && !compoundWriteHasCompleteWrite(subMerge, newEmptyPath())) {
          return null;
        } else {
          const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
          return compoundWriteApply(subMerge, layeredCache);
        }
      }
    } else {
      const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
      if (!includeHiddenWrites && compoundWriteIsEmpty(merge)) {
        return completeServerCache;
      } else {
        if (!includeHiddenWrites && completeServerCache == null && !compoundWriteHasCompleteWrite(merge, newEmptyPath())) {
          return null;
        } else {
          const filter = function(write) {
            return (write.visible || includeHiddenWrites) && (!writeIdsToExclude || !~writeIdsToExclude.indexOf(write.writeId)) && (pathContains(write.path, treePath) || pathContains(treePath, write.path));
          };
          const mergeAtPath = writeTreeLayerTree_(writeTree.allWrites, filter, treePath);
          const layeredCache = completeServerCache || ChildrenNode.EMPTY_NODE;
          return compoundWriteApply(mergeAtPath, layeredCache);
        }
      }
    }
  }
  function writeTreeCalcCompleteEventChildren(writeTree, treePath, completeServerChildren) {
    let completeChildren = ChildrenNode.EMPTY_NODE;
    const topLevelSet = compoundWriteGetCompleteNode(writeTree.visibleWrites, treePath);
    if (topLevelSet) {
      if (!topLevelSet.isLeafNode()) {
        topLevelSet.forEachChild(PRIORITY_INDEX, (childName, childSnap) => {
          completeChildren = completeChildren.updateImmediateChild(childName, childSnap);
        });
      }
      return completeChildren;
    } else if (completeServerChildren) {
      const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
      completeServerChildren.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
        const node = compoundWriteApply(compoundWriteChildCompoundWrite(merge, new Path(childName)), childNode);
        completeChildren = completeChildren.updateImmediateChild(childName, node);
      });
      compoundWriteGetCompleteChildren(merge).forEach((namedNode) => {
        completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
      });
      return completeChildren;
    } else {
      const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
      compoundWriteGetCompleteChildren(merge).forEach((namedNode) => {
        completeChildren = completeChildren.updateImmediateChild(namedNode.name, namedNode.node);
      });
      return completeChildren;
    }
  }
  function writeTreeCalcEventCacheAfterServerOverwrite(writeTree, treePath, childPath, existingEventSnap, existingServerSnap) {
    assert(existingEventSnap || existingServerSnap, "Either existingEventSnap or existingServerSnap must exist");
    const path = pathChild(treePath, childPath);
    if (compoundWriteHasCompleteWrite(writeTree.visibleWrites, path)) {
      return null;
    } else {
      const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
      if (compoundWriteIsEmpty(childMerge)) {
        return existingServerSnap.getChild(childPath);
      } else {
        return compoundWriteApply(childMerge, existingServerSnap.getChild(childPath));
      }
    }
  }
  function writeTreeCalcCompleteChild(writeTree, treePath, childKey, existingServerSnap) {
    const path = pathChild(treePath, childKey);
    const shadowingNode = compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
    if (shadowingNode != null) {
      return shadowingNode;
    } else {
      if (existingServerSnap.isCompleteForChild(childKey)) {
        const childMerge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, path);
        return compoundWriteApply(childMerge, existingServerSnap.getNode().getImmediateChild(childKey));
      } else {
        return null;
      }
    }
  }
  function writeTreeShadowingWrite(writeTree, path) {
    return compoundWriteGetCompleteNode(writeTree.visibleWrites, path);
  }
  function writeTreeCalcIndexedSlice(writeTree, treePath, completeServerData, startPost, count, reverse, index2) {
    let toIterate;
    const merge = compoundWriteChildCompoundWrite(writeTree.visibleWrites, treePath);
    const shadowingNode = compoundWriteGetCompleteNode(merge, newEmptyPath());
    if (shadowingNode != null) {
      toIterate = shadowingNode;
    } else if (completeServerData != null) {
      toIterate = compoundWriteApply(merge, completeServerData);
    } else {
      return [];
    }
    toIterate = toIterate.withIndex(index2);
    if (!toIterate.isEmpty() && !toIterate.isLeafNode()) {
      const nodes = [];
      const cmp = index2.getCompare();
      const iter = reverse ? toIterate.getReverseIteratorFrom(startPost, index2) : toIterate.getIteratorFrom(startPost, index2);
      let next = iter.getNext();
      while (next && nodes.length < count) {
        if (cmp(next, startPost) !== 0) {
          nodes.push(next);
        }
        next = iter.getNext();
      }
      return nodes;
    } else {
      return [];
    }
  }
  function newWriteTree() {
    return {
      visibleWrites: CompoundWrite.empty(),
      allWrites: [],
      lastWriteId: -1
    };
  }
  function writeTreeRefCalcCompleteEventCache(writeTreeRef, completeServerCache, writeIdsToExclude, includeHiddenWrites) {
    return writeTreeCalcCompleteEventCache(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerCache, writeIdsToExclude, includeHiddenWrites);
  }
  function writeTreeRefCalcCompleteEventChildren(writeTreeRef, completeServerChildren) {
    return writeTreeCalcCompleteEventChildren(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerChildren);
  }
  function writeTreeRefCalcEventCacheAfterServerOverwrite(writeTreeRef, path, existingEventSnap, existingServerSnap) {
    return writeTreeCalcEventCacheAfterServerOverwrite(writeTreeRef.writeTree, writeTreeRef.treePath, path, existingEventSnap, existingServerSnap);
  }
  function writeTreeRefShadowingWrite(writeTreeRef, path) {
    return writeTreeShadowingWrite(writeTreeRef.writeTree, pathChild(writeTreeRef.treePath, path));
  }
  function writeTreeRefCalcIndexedSlice(writeTreeRef, completeServerData, startPost, count, reverse, index2) {
    return writeTreeCalcIndexedSlice(writeTreeRef.writeTree, writeTreeRef.treePath, completeServerData, startPost, count, reverse, index2);
  }
  function writeTreeRefCalcCompleteChild(writeTreeRef, childKey, existingServerCache) {
    return writeTreeCalcCompleteChild(writeTreeRef.writeTree, writeTreeRef.treePath, childKey, existingServerCache);
  }
  function writeTreeRefChild(writeTreeRef, childName) {
    return newWriteTreeRef(pathChild(writeTreeRef.treePath, childName), writeTreeRef.writeTree);
  }
  function newWriteTreeRef(path, writeTree) {
    return {
      treePath: path,
      writeTree
    };
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class ChildChangeAccumulator {
    constructor() {
      this.changeMap = /* @__PURE__ */ new Map();
    }
    trackChildChange(change) {
      const type = change.type;
      const childKey = change.childName;
      assert(type === "child_added" || type === "child_changed" || type === "child_removed", "Only child changes supported for tracking");
      assert(childKey !== ".priority", "Only non-priority child changes can be tracked.");
      const oldChange = this.changeMap.get(childKey);
      if (oldChange) {
        const oldType = oldChange.type;
        if (type === "child_added" && oldType === "child_removed") {
          this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.snapshotNode));
        } else if (type === "child_removed" && oldType === "child_added") {
          this.changeMap.delete(childKey);
        } else if (type === "child_removed" && oldType === "child_changed") {
          this.changeMap.set(childKey, changeChildRemoved(childKey, oldChange.oldSnap));
        } else if (type === "child_changed" && oldType === "child_added") {
          this.changeMap.set(childKey, changeChildAdded(childKey, change.snapshotNode));
        } else if (type === "child_changed" && oldType === "child_changed") {
          this.changeMap.set(childKey, changeChildChanged(childKey, change.snapshotNode, oldChange.oldSnap));
        } else {
          throw assertionError("Illegal combination of changes: " + change + " occurred after " + oldChange);
        }
      } else {
        this.changeMap.set(childKey, change);
      }
    }
    getChanges() {
      return Array.from(this.changeMap.values());
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class NoCompleteChildSource_ {
    getCompleteChild(childKey) {
      return null;
    }
    getChildAfterChild(index2, child2, reverse) {
      return null;
    }
  }
  const NO_COMPLETE_CHILD_SOURCE = new NoCompleteChildSource_();
  class WriteTreeCompleteChildSource {
    constructor(writes_, viewCache_, optCompleteServerCache_ = null) {
      this.writes_ = writes_;
      this.viewCache_ = viewCache_;
      this.optCompleteServerCache_ = optCompleteServerCache_;
    }
    getCompleteChild(childKey) {
      const node = this.viewCache_.eventCache;
      if (node.isCompleteForChild(childKey)) {
        return node.getNode().getImmediateChild(childKey);
      } else {
        const serverNode = this.optCompleteServerCache_ != null ? new CacheNode(this.optCompleteServerCache_, true, false) : this.viewCache_.serverCache;
        return writeTreeRefCalcCompleteChild(this.writes_, childKey, serverNode);
      }
    }
    getChildAfterChild(index2, child2, reverse) {
      const completeServerData = this.optCompleteServerCache_ != null ? this.optCompleteServerCache_ : viewCacheGetCompleteServerSnap(this.viewCache_);
      const nodes = writeTreeRefCalcIndexedSlice(this.writes_, completeServerData, child2, 1, reverse, index2);
      if (nodes.length === 0) {
        return null;
      } else {
        return nodes[0];
      }
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function newViewProcessor(filter) {
    return { filter };
  }
  function viewProcessorAssertIndexed(viewProcessor, viewCache) {
    assert(viewCache.eventCache.getNode().isIndexed(viewProcessor.filter.getIndex()), "Event snap not indexed");
    assert(viewCache.serverCache.getNode().isIndexed(viewProcessor.filter.getIndex()), "Server snap not indexed");
  }
  function viewProcessorApplyOperation(viewProcessor, oldViewCache, operation, writesCache, completeCache) {
    const accumulator = new ChildChangeAccumulator();
    let newViewCache2, filterServerNode;
    if (operation.type === OperationType.OVERWRITE) {
      const overwrite = operation;
      if (overwrite.source.fromUser) {
        newViewCache2 = viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, accumulator);
      } else {
        assert(overwrite.source.fromServer, "Unknown source.");
        filterServerNode = overwrite.source.tagged || oldViewCache.serverCache.isFiltered() && !pathIsEmpty(overwrite.path);
        newViewCache2 = viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, overwrite.path, overwrite.snap, writesCache, completeCache, filterServerNode, accumulator);
      }
    } else if (operation.type === OperationType.MERGE) {
      const merge = operation;
      if (merge.source.fromUser) {
        newViewCache2 = viewProcessorApplyUserMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, accumulator);
      } else {
        assert(merge.source.fromServer, "Unknown source.");
        filterServerNode = merge.source.tagged || oldViewCache.serverCache.isFiltered();
        newViewCache2 = viewProcessorApplyServerMerge(viewProcessor, oldViewCache, merge.path, merge.children, writesCache, completeCache, filterServerNode, accumulator);
      }
    } else if (operation.type === OperationType.ACK_USER_WRITE) {
      const ackUserWrite = operation;
      if (!ackUserWrite.revert) {
        newViewCache2 = viewProcessorAckUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, ackUserWrite.affectedTree, writesCache, completeCache, accumulator);
      } else {
        newViewCache2 = viewProcessorRevertUserWrite(viewProcessor, oldViewCache, ackUserWrite.path, writesCache, completeCache, accumulator);
      }
    } else if (operation.type === OperationType.LISTEN_COMPLETE) {
      newViewCache2 = viewProcessorListenComplete(viewProcessor, oldViewCache, operation.path, writesCache, accumulator);
    } else {
      throw assertionError("Unknown operation type: " + operation.type);
    }
    const changes = accumulator.getChanges();
    viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache2, changes);
    return { viewCache: newViewCache2, changes };
  }
  function viewProcessorMaybeAddValueEvent(oldViewCache, newViewCache2, accumulator) {
    const eventSnap = newViewCache2.eventCache;
    if (eventSnap.isFullyInitialized()) {
      const isLeafOrEmpty = eventSnap.getNode().isLeafNode() || eventSnap.getNode().isEmpty();
      const oldCompleteSnap = viewCacheGetCompleteEventSnap(oldViewCache);
      if (accumulator.length > 0 || !oldViewCache.eventCache.isFullyInitialized() || isLeafOrEmpty && !eventSnap.getNode().equals(oldCompleteSnap) || !eventSnap.getNode().getPriority().equals(oldCompleteSnap.getPriority())) {
        accumulator.push(changeValue(viewCacheGetCompleteEventSnap(newViewCache2)));
      }
    }
  }
  function viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, viewCache, changePath, writesCache, source, accumulator) {
    const oldEventSnap = viewCache.eventCache;
    if (writeTreeRefShadowingWrite(writesCache, changePath) != null) {
      return viewCache;
    } else {
      let newEventCache, serverNode;
      if (pathIsEmpty(changePath)) {
        assert(viewCache.serverCache.isFullyInitialized(), "If change path is empty, we must have complete server data");
        if (viewCache.serverCache.isFiltered()) {
          const serverCache = viewCacheGetCompleteServerSnap(viewCache);
          const completeChildren = serverCache instanceof ChildrenNode ? serverCache : ChildrenNode.EMPTY_NODE;
          const completeEventChildren = writeTreeRefCalcCompleteEventChildren(writesCache, completeChildren);
          newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeEventChildren, accumulator);
        } else {
          const completeNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
          newEventCache = viewProcessor.filter.updateFullNode(viewCache.eventCache.getNode(), completeNode, accumulator);
        }
      } else {
        const childKey = pathGetFront(changePath);
        if (childKey === ".priority") {
          assert(pathGetLength(changePath) === 1, "Can't have a priority with additional path components");
          const oldEventNode = oldEventSnap.getNode();
          serverNode = viewCache.serverCache.getNode();
          const updatedPriority = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventNode, serverNode);
          if (updatedPriority != null) {
            newEventCache = viewProcessor.filter.updatePriority(oldEventNode, updatedPriority);
          } else {
            newEventCache = oldEventSnap.getNode();
          }
        } else {
          const childChangePath = pathPopFront(changePath);
          let newEventChild;
          if (oldEventSnap.isCompleteForChild(childKey)) {
            serverNode = viewCache.serverCache.getNode();
            const eventChildUpdate = writeTreeRefCalcEventCacheAfterServerOverwrite(writesCache, changePath, oldEventSnap.getNode(), serverNode);
            if (eventChildUpdate != null) {
              newEventChild = oldEventSnap.getNode().getImmediateChild(childKey).updateChild(childChangePath, eventChildUpdate);
            } else {
              newEventChild = oldEventSnap.getNode().getImmediateChild(childKey);
            }
          } else {
            newEventChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
          }
          if (newEventChild != null) {
            newEventCache = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newEventChild, childChangePath, source, accumulator);
          } else {
            newEventCache = oldEventSnap.getNode();
          }
        }
      }
      return viewCacheUpdateEventSnap(viewCache, newEventCache, oldEventSnap.isFullyInitialized() || pathIsEmpty(changePath), viewProcessor.filter.filtersNodes());
    }
  }
  function viewProcessorApplyServerOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, filterServerNode, accumulator) {
    const oldServerSnap = oldViewCache.serverCache;
    let newServerCache;
    const serverFilter = filterServerNode ? viewProcessor.filter : viewProcessor.filter.getIndexedFilter();
    if (pathIsEmpty(changePath)) {
      newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), changedSnap, null);
    } else if (serverFilter.filtersNodes() && !oldServerSnap.isFiltered()) {
      const newServerNode = oldServerSnap.getNode().updateChild(changePath, changedSnap);
      newServerCache = serverFilter.updateFullNode(oldServerSnap.getNode(), newServerNode, null);
    } else {
      const childKey = pathGetFront(changePath);
      if (!oldServerSnap.isCompleteForPath(changePath) && pathGetLength(changePath) > 1) {
        return oldViewCache;
      }
      const childChangePath = pathPopFront(changePath);
      const childNode = oldServerSnap.getNode().getImmediateChild(childKey);
      const newChildNode = childNode.updateChild(childChangePath, changedSnap);
      if (childKey === ".priority") {
        newServerCache = serverFilter.updatePriority(oldServerSnap.getNode(), newChildNode);
      } else {
        newServerCache = serverFilter.updateChild(oldServerSnap.getNode(), childKey, newChildNode, childChangePath, NO_COMPLETE_CHILD_SOURCE, null);
      }
    }
    const newViewCache2 = viewCacheUpdateServerSnap(oldViewCache, newServerCache, oldServerSnap.isFullyInitialized() || pathIsEmpty(changePath), serverFilter.filtersNodes());
    const source = new WriteTreeCompleteChildSource(writesCache, newViewCache2, completeCache);
    return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache2, changePath, writesCache, source, accumulator);
  }
  function viewProcessorApplyUserOverwrite(viewProcessor, oldViewCache, changePath, changedSnap, writesCache, completeCache, accumulator) {
    const oldEventSnap = oldViewCache.eventCache;
    let newViewCache2, newEventCache;
    const source = new WriteTreeCompleteChildSource(writesCache, oldViewCache, completeCache);
    if (pathIsEmpty(changePath)) {
      newEventCache = viewProcessor.filter.updateFullNode(oldViewCache.eventCache.getNode(), changedSnap, accumulator);
      newViewCache2 = viewCacheUpdateEventSnap(oldViewCache, newEventCache, true, viewProcessor.filter.filtersNodes());
    } else {
      const childKey = pathGetFront(changePath);
      if (childKey === ".priority") {
        newEventCache = viewProcessor.filter.updatePriority(oldViewCache.eventCache.getNode(), changedSnap);
        newViewCache2 = viewCacheUpdateEventSnap(oldViewCache, newEventCache, oldEventSnap.isFullyInitialized(), oldEventSnap.isFiltered());
      } else {
        const childChangePath = pathPopFront(changePath);
        const oldChild = oldEventSnap.getNode().getImmediateChild(childKey);
        let newChild;
        if (pathIsEmpty(childChangePath)) {
          newChild = changedSnap;
        } else {
          const childNode = source.getCompleteChild(childKey);
          if (childNode != null) {
            if (pathGetBack(childChangePath) === ".priority" && childNode.getChild(pathParent(childChangePath)).isEmpty()) {
              newChild = childNode;
            } else {
              newChild = childNode.updateChild(childChangePath, changedSnap);
            }
          } else {
            newChild = ChildrenNode.EMPTY_NODE;
          }
        }
        if (!oldChild.equals(newChild)) {
          const newEventSnap = viewProcessor.filter.updateChild(oldEventSnap.getNode(), childKey, newChild, childChangePath, source, accumulator);
          newViewCache2 = viewCacheUpdateEventSnap(oldViewCache, newEventSnap, oldEventSnap.isFullyInitialized(), viewProcessor.filter.filtersNodes());
        } else {
          newViewCache2 = oldViewCache;
        }
      }
    }
    return newViewCache2;
  }
  function viewProcessorCacheHasChild(viewCache, childKey) {
    return viewCache.eventCache.isCompleteForChild(childKey);
  }
  function viewProcessorApplyUserMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, accumulator) {
    let curViewCache = viewCache;
    changedChildren.foreach((relativePath, childNode) => {
      const writePath = pathChild(path, relativePath);
      if (viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
        curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
      }
    });
    changedChildren.foreach((relativePath, childNode) => {
      const writePath = pathChild(path, relativePath);
      if (!viewProcessorCacheHasChild(viewCache, pathGetFront(writePath))) {
        curViewCache = viewProcessorApplyUserOverwrite(viewProcessor, curViewCache, writePath, childNode, writesCache, serverCache, accumulator);
      }
    });
    return curViewCache;
  }
  function viewProcessorApplyMerge(viewProcessor, node, merge) {
    merge.foreach((relativePath, childNode) => {
      node = node.updateChild(relativePath, childNode);
    });
    return node;
  }
  function viewProcessorApplyServerMerge(viewProcessor, viewCache, path, changedChildren, writesCache, serverCache, filterServerNode, accumulator) {
    if (viewCache.serverCache.getNode().isEmpty() && !viewCache.serverCache.isFullyInitialized()) {
      return viewCache;
    }
    let curViewCache = viewCache;
    let viewMergeTree;
    if (pathIsEmpty(path)) {
      viewMergeTree = changedChildren;
    } else {
      viewMergeTree = new ImmutableTree(null).setTree(path, changedChildren);
    }
    const serverNode = viewCache.serverCache.getNode();
    viewMergeTree.children.inorderTraversal((childKey, childTree) => {
      if (serverNode.hasChild(childKey)) {
        const serverChild = viewCache.serverCache.getNode().getImmediateChild(childKey);
        const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childTree);
        curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
      }
    });
    viewMergeTree.children.inorderTraversal((childKey, childMergeTree) => {
      const isUnknownDeepMerge = !viewCache.serverCache.isCompleteForChild(childKey) && childMergeTree.value === null;
      if (!serverNode.hasChild(childKey) && !isUnknownDeepMerge) {
        const serverChild = viewCache.serverCache.getNode().getImmediateChild(childKey);
        const newChild = viewProcessorApplyMerge(viewProcessor, serverChild, childMergeTree);
        curViewCache = viewProcessorApplyServerOverwrite(viewProcessor, curViewCache, new Path(childKey), newChild, writesCache, serverCache, filterServerNode, accumulator);
      }
    });
    return curViewCache;
  }
  function viewProcessorAckUserWrite(viewProcessor, viewCache, ackPath, affectedTree, writesCache, completeCache, accumulator) {
    if (writeTreeRefShadowingWrite(writesCache, ackPath) != null) {
      return viewCache;
    }
    const filterServerNode = viewCache.serverCache.isFiltered();
    const serverCache = viewCache.serverCache;
    if (affectedTree.value != null) {
      if (pathIsEmpty(ackPath) && serverCache.isFullyInitialized() || serverCache.isCompleteForPath(ackPath)) {
        return viewProcessorApplyServerOverwrite(viewProcessor, viewCache, ackPath, serverCache.getNode().getChild(ackPath), writesCache, completeCache, filterServerNode, accumulator);
      } else if (pathIsEmpty(ackPath)) {
        let changedChildren = new ImmutableTree(null);
        serverCache.getNode().forEachChild(KEY_INDEX, (name2, node) => {
          changedChildren = changedChildren.set(new Path(name2), node);
        });
        return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
      } else {
        return viewCache;
      }
    } else {
      let changedChildren = new ImmutableTree(null);
      affectedTree.foreach((mergePath, value) => {
        const serverCachePath = pathChild(ackPath, mergePath);
        if (serverCache.isCompleteForPath(serverCachePath)) {
          changedChildren = changedChildren.set(mergePath, serverCache.getNode().getChild(serverCachePath));
        }
      });
      return viewProcessorApplyServerMerge(viewProcessor, viewCache, ackPath, changedChildren, writesCache, completeCache, filterServerNode, accumulator);
    }
  }
  function viewProcessorListenComplete(viewProcessor, viewCache, path, writesCache, accumulator) {
    const oldServerNode = viewCache.serverCache;
    const newViewCache2 = viewCacheUpdateServerSnap(viewCache, oldServerNode.getNode(), oldServerNode.isFullyInitialized() || pathIsEmpty(path), oldServerNode.isFiltered());
    return viewProcessorGenerateEventCacheAfterServerEvent(viewProcessor, newViewCache2, path, writesCache, NO_COMPLETE_CHILD_SOURCE, accumulator);
  }
  function viewProcessorRevertUserWrite(viewProcessor, viewCache, path, writesCache, completeServerCache, accumulator) {
    let complete;
    if (writeTreeRefShadowingWrite(writesCache, path) != null) {
      return viewCache;
    } else {
      const source = new WriteTreeCompleteChildSource(writesCache, viewCache, completeServerCache);
      const oldEventCache = viewCache.eventCache.getNode();
      let newEventCache;
      if (pathIsEmpty(path) || pathGetFront(path) === ".priority") {
        let newNode;
        if (viewCache.serverCache.isFullyInitialized()) {
          newNode = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
        } else {
          const serverChildren = viewCache.serverCache.getNode();
          assert(serverChildren instanceof ChildrenNode, "serverChildren would be complete if leaf node");
          newNode = writeTreeRefCalcCompleteEventChildren(writesCache, serverChildren);
        }
        newNode = newNode;
        newEventCache = viewProcessor.filter.updateFullNode(oldEventCache, newNode, accumulator);
      } else {
        const childKey = pathGetFront(path);
        let newChild = writeTreeRefCalcCompleteChild(writesCache, childKey, viewCache.serverCache);
        if (newChild == null && viewCache.serverCache.isCompleteForChild(childKey)) {
          newChild = oldEventCache.getImmediateChild(childKey);
        }
        if (newChild != null) {
          newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, newChild, pathPopFront(path), source, accumulator);
        } else if (viewCache.eventCache.getNode().hasChild(childKey)) {
          newEventCache = viewProcessor.filter.updateChild(oldEventCache, childKey, ChildrenNode.EMPTY_NODE, pathPopFront(path), source, accumulator);
        } else {
          newEventCache = oldEventCache;
        }
        if (newEventCache.isEmpty() && viewCache.serverCache.isFullyInitialized()) {
          complete = writeTreeRefCalcCompleteEventCache(writesCache, viewCacheGetCompleteServerSnap(viewCache));
          if (complete.isLeafNode()) {
            newEventCache = viewProcessor.filter.updateFullNode(newEventCache, complete, accumulator);
          }
        }
      }
      complete = viewCache.serverCache.isFullyInitialized() || writeTreeRefShadowingWrite(writesCache, newEmptyPath()) != null;
      return viewCacheUpdateEventSnap(viewCache, newEventCache, complete, viewProcessor.filter.filtersNodes());
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class View {
    constructor(query_, initialViewCache) {
      this.query_ = query_;
      this.eventRegistrations_ = [];
      const params = this.query_._queryParams;
      const indexFilter = new IndexedFilter(params.getIndex());
      const filter = queryParamsGetNodeFilter(params);
      this.processor_ = newViewProcessor(filter);
      const initialServerCache = initialViewCache.serverCache;
      const initialEventCache = initialViewCache.eventCache;
      const serverSnap = indexFilter.updateFullNode(ChildrenNode.EMPTY_NODE, initialServerCache.getNode(), null);
      const eventSnap = filter.updateFullNode(ChildrenNode.EMPTY_NODE, initialEventCache.getNode(), null);
      const newServerCache = new CacheNode(serverSnap, initialServerCache.isFullyInitialized(), indexFilter.filtersNodes());
      const newEventCache = new CacheNode(eventSnap, initialEventCache.isFullyInitialized(), filter.filtersNodes());
      this.viewCache_ = newViewCache(newEventCache, newServerCache);
      this.eventGenerator_ = new EventGenerator(this.query_);
    }
    get query() {
      return this.query_;
    }
  }
  function viewGetServerCache(view) {
    return view.viewCache_.serverCache.getNode();
  }
  function viewGetCompleteNode(view) {
    return viewCacheGetCompleteEventSnap(view.viewCache_);
  }
  function viewGetCompleteServerCache(view, path) {
    const cache = viewCacheGetCompleteServerSnap(view.viewCache_);
    if (cache) {
      if (view.query._queryParams.loadsAllData() || !pathIsEmpty(path) && !cache.getImmediateChild(pathGetFront(path)).isEmpty()) {
        return cache.getChild(path);
      }
    }
    return null;
  }
  function viewIsEmpty(view) {
    return view.eventRegistrations_.length === 0;
  }
  function viewAddEventRegistration(view, eventRegistration) {
    view.eventRegistrations_.push(eventRegistration);
  }
  function viewRemoveEventRegistration(view, eventRegistration, cancelError) {
    const cancelEvents = [];
    if (cancelError) {
      assert(eventRegistration == null, "A cancel should cancel all event registrations.");
      const path = view.query._path;
      view.eventRegistrations_.forEach((registration) => {
        const maybeEvent = registration.createCancelEvent(cancelError, path);
        if (maybeEvent) {
          cancelEvents.push(maybeEvent);
        }
      });
    }
    if (eventRegistration) {
      let remaining = [];
      for (let i2 = 0; i2 < view.eventRegistrations_.length; ++i2) {
        const existing = view.eventRegistrations_[i2];
        if (!existing.matches(eventRegistration)) {
          remaining.push(existing);
        } else if (eventRegistration.hasAnyCallback()) {
          remaining = remaining.concat(view.eventRegistrations_.slice(i2 + 1));
          break;
        }
      }
      view.eventRegistrations_ = remaining;
    } else {
      view.eventRegistrations_ = [];
    }
    return cancelEvents;
  }
  function viewApplyOperation(view, operation, writesCache, completeServerCache) {
    if (operation.type === OperationType.MERGE && operation.source.queryId !== null) {
      assert(viewCacheGetCompleteServerSnap(view.viewCache_), "We should always have a full cache before handling merges");
      assert(viewCacheGetCompleteEventSnap(view.viewCache_), "Missing event cache, even though we have a server cache");
    }
    const oldViewCache = view.viewCache_;
    const result = viewProcessorApplyOperation(view.processor_, oldViewCache, operation, writesCache, completeServerCache);
    viewProcessorAssertIndexed(view.processor_, result.viewCache);
    assert(result.viewCache.serverCache.isFullyInitialized() || !oldViewCache.serverCache.isFullyInitialized(), "Once a server snap is complete, it should never go back");
    view.viewCache_ = result.viewCache;
    return viewGenerateEventsForChanges_(view, result.changes, result.viewCache.eventCache.getNode(), null);
  }
  function viewGetInitialEvents(view, registration) {
    const eventSnap = view.viewCache_.eventCache;
    const initialChanges = [];
    if (!eventSnap.getNode().isLeafNode()) {
      const eventNode = eventSnap.getNode();
      eventNode.forEachChild(PRIORITY_INDEX, (key, childNode) => {
        initialChanges.push(changeChildAdded(key, childNode));
      });
    }
    if (eventSnap.isFullyInitialized()) {
      initialChanges.push(changeValue(eventSnap.getNode()));
    }
    return viewGenerateEventsForChanges_(view, initialChanges, eventSnap.getNode(), registration);
  }
  function viewGenerateEventsForChanges_(view, changes, eventCache, eventRegistration) {
    const registrations = eventRegistration ? [eventRegistration] : view.eventRegistrations_;
    return eventGeneratorGenerateEventsForChanges(view.eventGenerator_, changes, eventCache, registrations);
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  let referenceConstructor$1;
  class SyncPoint {
    constructor() {
      this.views = /* @__PURE__ */ new Map();
    }
  }
  function syncPointSetReferenceConstructor(val) {
    assert(!referenceConstructor$1, "__referenceConstructor has already been defined");
    referenceConstructor$1 = val;
  }
  function syncPointGetReferenceConstructor() {
    assert(referenceConstructor$1, "Reference.ts has not been loaded");
    return referenceConstructor$1;
  }
  function syncPointIsEmpty(syncPoint) {
    return syncPoint.views.size === 0;
  }
  function syncPointApplyOperation(syncPoint, operation, writesCache, optCompleteServerCache) {
    const queryId = operation.source.queryId;
    if (queryId !== null) {
      const view = syncPoint.views.get(queryId);
      assert(view != null, "SyncTree gave us an op for an invalid query.");
      return viewApplyOperation(view, operation, writesCache, optCompleteServerCache);
    } else {
      let events2 = [];
      for (const view of syncPoint.views.values()) {
        events2 = events2.concat(viewApplyOperation(view, operation, writesCache, optCompleteServerCache));
      }
      return events2;
    }
  }
  function syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete) {
    const queryId = query._queryIdentifier;
    const view = syncPoint.views.get(queryId);
    if (!view) {
      let eventCache = writeTreeRefCalcCompleteEventCache(writesCache, serverCacheComplete ? serverCache : null);
      let eventCacheComplete = false;
      if (eventCache) {
        eventCacheComplete = true;
      } else if (serverCache instanceof ChildrenNode) {
        eventCache = writeTreeRefCalcCompleteEventChildren(writesCache, serverCache);
        eventCacheComplete = false;
      } else {
        eventCache = ChildrenNode.EMPTY_NODE;
        eventCacheComplete = false;
      }
      const viewCache = newViewCache(new CacheNode(eventCache, eventCacheComplete, false), new CacheNode(serverCache, serverCacheComplete, false));
      return new View(query, viewCache);
    }
    return view;
  }
  function syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete) {
    const view = syncPointGetView(syncPoint, query, writesCache, serverCache, serverCacheComplete);
    if (!syncPoint.views.has(query._queryIdentifier)) {
      syncPoint.views.set(query._queryIdentifier, view);
    }
    viewAddEventRegistration(view, eventRegistration);
    return viewGetInitialEvents(view, eventRegistration);
  }
  function syncPointRemoveEventRegistration(syncPoint, query, eventRegistration, cancelError) {
    const queryId = query._queryIdentifier;
    const removed = [];
    let cancelEvents = [];
    const hadCompleteView = syncPointHasCompleteView(syncPoint);
    if (queryId === "default") {
      for (const [viewQueryId, view] of syncPoint.views.entries()) {
        cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
        if (viewIsEmpty(view)) {
          syncPoint.views.delete(viewQueryId);
          if (!view.query._queryParams.loadsAllData()) {
            removed.push(view.query);
          }
        }
      }
    } else {
      const view = syncPoint.views.get(queryId);
      if (view) {
        cancelEvents = cancelEvents.concat(viewRemoveEventRegistration(view, eventRegistration, cancelError));
        if (viewIsEmpty(view)) {
          syncPoint.views.delete(queryId);
          if (!view.query._queryParams.loadsAllData()) {
            removed.push(view.query);
          }
        }
      }
    }
    if (hadCompleteView && !syncPointHasCompleteView(syncPoint)) {
      removed.push(new (syncPointGetReferenceConstructor())(query._repo, query._path));
    }
    return { removed, events: cancelEvents };
  }
  function syncPointGetQueryViews(syncPoint) {
    const result = [];
    for (const view of syncPoint.views.values()) {
      if (!view.query._queryParams.loadsAllData()) {
        result.push(view);
      }
    }
    return result;
  }
  function syncPointGetCompleteServerCache(syncPoint, path) {
    let serverCache = null;
    for (const view of syncPoint.views.values()) {
      serverCache = serverCache || viewGetCompleteServerCache(view, path);
    }
    return serverCache;
  }
  function syncPointViewForQuery(syncPoint, query) {
    const params = query._queryParams;
    if (params.loadsAllData()) {
      return syncPointGetCompleteView(syncPoint);
    } else {
      const queryId = query._queryIdentifier;
      return syncPoint.views.get(queryId);
    }
  }
  function syncPointViewExistsForQuery(syncPoint, query) {
    return syncPointViewForQuery(syncPoint, query) != null;
  }
  function syncPointHasCompleteView(syncPoint) {
    return syncPointGetCompleteView(syncPoint) != null;
  }
  function syncPointGetCompleteView(syncPoint) {
    for (const view of syncPoint.views.values()) {
      if (view.query._queryParams.loadsAllData()) {
        return view;
      }
    }
    return null;
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  let referenceConstructor;
  function syncTreeSetReferenceConstructor(val) {
    assert(!referenceConstructor, "__referenceConstructor has already been defined");
    referenceConstructor = val;
  }
  function syncTreeGetReferenceConstructor() {
    assert(referenceConstructor, "Reference.ts has not been loaded");
    return referenceConstructor;
  }
  let syncTreeNextQueryTag_ = 1;
  class SyncTree {
    /**
     * @param listenProvider_ - Used by SyncTree to start / stop listening
     *   to server data.
     */
    constructor(listenProvider_) {
      this.listenProvider_ = listenProvider_;
      this.syncPointTree_ = new ImmutableTree(null);
      this.pendingWriteTree_ = newWriteTree();
      this.tagToQueryMap = /* @__PURE__ */ new Map();
      this.queryToTagMap = /* @__PURE__ */ new Map();
    }
  }
  function syncTreeApplyUserOverwrite(syncTree, path, newData, writeId, visible) {
    writeTreeAddOverwrite(syncTree.pendingWriteTree_, path, newData, writeId, visible);
    if (!visible) {
      return [];
    } else {
      return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceUser(), path, newData));
    }
  }
  function syncTreeAckUserWrite(syncTree, writeId, revert = false) {
    const write = writeTreeGetWrite(syncTree.pendingWriteTree_, writeId);
    const needToReevaluate = writeTreeRemoveWrite(syncTree.pendingWriteTree_, writeId);
    if (!needToReevaluate) {
      return [];
    } else {
      let affectedTree = new ImmutableTree(null);
      if (write.snap != null) {
        affectedTree = affectedTree.set(newEmptyPath(), true);
      } else {
        each(write.children, (pathString) => {
          affectedTree = affectedTree.set(new Path(pathString), true);
        });
      }
      return syncTreeApplyOperationToSyncPoints_(syncTree, new AckUserWrite(write.path, affectedTree, revert));
    }
  }
  function syncTreeApplyServerOverwrite(syncTree, path, newData) {
    return syncTreeApplyOperationToSyncPoints_(syncTree, new Overwrite(newOperationSourceServer(), path, newData));
  }
  function syncTreeApplyServerMerge(syncTree, path, changedChildren) {
    const changeTree = ImmutableTree.fromObject(changedChildren);
    return syncTreeApplyOperationToSyncPoints_(syncTree, new Merge(newOperationSourceServer(), path, changeTree));
  }
  function syncTreeApplyListenComplete(syncTree, path) {
    return syncTreeApplyOperationToSyncPoints_(syncTree, new ListenComplete(newOperationSourceServer(), path));
  }
  function syncTreeApplyTaggedListenComplete(syncTree, path, tag) {
    const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
    if (queryKey) {
      const r2 = syncTreeParseQueryKey_(queryKey);
      const queryPath = r2.path, queryId = r2.queryId;
      const relativePath = newRelativePath(queryPath, path);
      const op = new ListenComplete(newOperationSourceServerTaggedQuery(queryId), relativePath);
      return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
    } else {
      return [];
    }
  }
  function syncTreeRemoveEventRegistration(syncTree, query, eventRegistration, cancelError, skipListenerDedup = false) {
    const path = query._path;
    const maybeSyncPoint = syncTree.syncPointTree_.get(path);
    let cancelEvents = [];
    if (maybeSyncPoint && (query._queryIdentifier === "default" || syncPointViewExistsForQuery(maybeSyncPoint, query))) {
      const removedAndEvents = syncPointRemoveEventRegistration(maybeSyncPoint, query, eventRegistration, cancelError);
      if (syncPointIsEmpty(maybeSyncPoint)) {
        syncTree.syncPointTree_ = syncTree.syncPointTree_.remove(path);
      }
      const removed = removedAndEvents.removed;
      cancelEvents = removedAndEvents.events;
      if (!skipListenerDedup) {
        const removingDefault = -1 !== removed.findIndex((query2) => {
          return query2._queryParams.loadsAllData();
        });
        const covered = syncTree.syncPointTree_.findOnPath(path, (relativePath, parentSyncPoint) => syncPointHasCompleteView(parentSyncPoint));
        if (removingDefault && !covered) {
          const subtree = syncTree.syncPointTree_.subtree(path);
          if (!subtree.isEmpty()) {
            const newViews = syncTreeCollectDistinctViewsForSubTree_(subtree);
            for (let i2 = 0; i2 < newViews.length; ++i2) {
              const view = newViews[i2], newQuery = view.query;
              const listener = syncTreeCreateListenerForView_(syncTree, view);
              syncTree.listenProvider_.startListening(syncTreeQueryForListening_(newQuery), syncTreeTagForQuery(syncTree, newQuery), listener.hashFn, listener.onComplete);
            }
          }
        }
        if (!covered && removed.length > 0 && !cancelError) {
          if (removingDefault) {
            const defaultTag = null;
            syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(query), defaultTag);
          } else {
            removed.forEach((queryToRemove) => {
              const tagToRemove = syncTree.queryToTagMap.get(syncTreeMakeQueryKey_(queryToRemove));
              syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToRemove), tagToRemove);
            });
          }
        }
      }
      syncTreeRemoveTags_(syncTree, removed);
    }
    return cancelEvents;
  }
  function syncTreeApplyTaggedQueryOverwrite(syncTree, path, snap, tag) {
    const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
    if (queryKey != null) {
      const r2 = syncTreeParseQueryKey_(queryKey);
      const queryPath = r2.path, queryId = r2.queryId;
      const relativePath = newRelativePath(queryPath, path);
      const op = new Overwrite(newOperationSourceServerTaggedQuery(queryId), relativePath, snap);
      return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
    } else {
      return [];
    }
  }
  function syncTreeApplyTaggedQueryMerge(syncTree, path, changedChildren, tag) {
    const queryKey = syncTreeQueryKeyForTag_(syncTree, tag);
    if (queryKey) {
      const r2 = syncTreeParseQueryKey_(queryKey);
      const queryPath = r2.path, queryId = r2.queryId;
      const relativePath = newRelativePath(queryPath, path);
      const changeTree = ImmutableTree.fromObject(changedChildren);
      const op = new Merge(newOperationSourceServerTaggedQuery(queryId), relativePath, changeTree);
      return syncTreeApplyTaggedOperation_(syncTree, queryPath, op);
    } else {
      return [];
    }
  }
  function syncTreeAddEventRegistration(syncTree, query, eventRegistration, skipSetupListener = false) {
    const path = query._path;
    let serverCache = null;
    let foundAncestorDefaultView = false;
    syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
      const relativePath = newRelativePath(pathToSyncPoint, path);
      serverCache = serverCache || syncPointGetCompleteServerCache(sp, relativePath);
      foundAncestorDefaultView = foundAncestorDefaultView || syncPointHasCompleteView(sp);
    });
    let syncPoint = syncTree.syncPointTree_.get(path);
    if (!syncPoint) {
      syncPoint = new SyncPoint();
      syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
    } else {
      foundAncestorDefaultView = foundAncestorDefaultView || syncPointHasCompleteView(syncPoint);
      serverCache = serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
    }
    let serverCacheComplete;
    if (serverCache != null) {
      serverCacheComplete = true;
    } else {
      serverCacheComplete = false;
      serverCache = ChildrenNode.EMPTY_NODE;
      const subtree = syncTree.syncPointTree_.subtree(path);
      subtree.foreachChild((childName, childSyncPoint) => {
        const completeCache = syncPointGetCompleteServerCache(childSyncPoint, newEmptyPath());
        if (completeCache) {
          serverCache = serverCache.updateImmediateChild(childName, completeCache);
        }
      });
    }
    const viewAlreadyExists = syncPointViewExistsForQuery(syncPoint, query);
    if (!viewAlreadyExists && !query._queryParams.loadsAllData()) {
      const queryKey = syncTreeMakeQueryKey_(query);
      assert(!syncTree.queryToTagMap.has(queryKey), "View does not exist, but we have a tag");
      const tag = syncTreeGetNextQueryTag_();
      syncTree.queryToTagMap.set(queryKey, tag);
      syncTree.tagToQueryMap.set(tag, queryKey);
    }
    const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, path);
    let events2 = syncPointAddEventRegistration(syncPoint, query, eventRegistration, writesCache, serverCache, serverCacheComplete);
    if (!viewAlreadyExists && !foundAncestorDefaultView && !skipSetupListener) {
      const view = syncPointViewForQuery(syncPoint, query);
      events2 = events2.concat(syncTreeSetupListener_(syncTree, query, view));
    }
    return events2;
  }
  function syncTreeCalcCompleteEventCache(syncTree, path, writeIdsToExclude) {
    const includeHiddenSets = true;
    const writeTree = syncTree.pendingWriteTree_;
    const serverCache = syncTree.syncPointTree_.findOnPath(path, (pathSoFar, syncPoint) => {
      const relativePath = newRelativePath(pathSoFar, path);
      const serverCache2 = syncPointGetCompleteServerCache(syncPoint, relativePath);
      if (serverCache2) {
        return serverCache2;
      }
    });
    return writeTreeCalcCompleteEventCache(writeTree, path, serverCache, writeIdsToExclude, includeHiddenSets);
  }
  function syncTreeGetServerValue(syncTree, query) {
    const path = query._path;
    let serverCache = null;
    syncTree.syncPointTree_.foreachOnPath(path, (pathToSyncPoint, sp) => {
      const relativePath = newRelativePath(pathToSyncPoint, path);
      serverCache = serverCache || syncPointGetCompleteServerCache(sp, relativePath);
    });
    let syncPoint = syncTree.syncPointTree_.get(path);
    if (!syncPoint) {
      syncPoint = new SyncPoint();
      syncTree.syncPointTree_ = syncTree.syncPointTree_.set(path, syncPoint);
    } else {
      serverCache = serverCache || syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
    }
    const serverCacheComplete = serverCache != null;
    const serverCacheNode = serverCacheComplete ? new CacheNode(serverCache, true, false) : null;
    const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, query._path);
    const view = syncPointGetView(syncPoint, query, writesCache, serverCacheComplete ? serverCacheNode.getNode() : ChildrenNode.EMPTY_NODE, serverCacheComplete);
    return viewGetCompleteNode(view);
  }
  function syncTreeApplyOperationToSyncPoints_(syncTree, operation) {
    return syncTreeApplyOperationHelper_(
      operation,
      syncTree.syncPointTree_,
      /*serverCache=*/
      null,
      writeTreeChildWrites(syncTree.pendingWriteTree_, newEmptyPath())
    );
  }
  function syncTreeApplyOperationHelper_(operation, syncPointTree, serverCache, writesCache) {
    if (pathIsEmpty(operation.path)) {
      return syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache);
    } else {
      const syncPoint = syncPointTree.get(newEmptyPath());
      if (serverCache == null && syncPoint != null) {
        serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
      }
      let events2 = [];
      const childName = pathGetFront(operation.path);
      const childOperation = operation.operationForChild(childName);
      const childTree = syncPointTree.children.get(childName);
      if (childTree && childOperation) {
        const childServerCache = serverCache ? serverCache.getImmediateChild(childName) : null;
        const childWritesCache = writeTreeRefChild(writesCache, childName);
        events2 = events2.concat(syncTreeApplyOperationHelper_(childOperation, childTree, childServerCache, childWritesCache));
      }
      if (syncPoint) {
        events2 = events2.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
      }
      return events2;
    }
  }
  function syncTreeApplyOperationDescendantsHelper_(operation, syncPointTree, serverCache, writesCache) {
    const syncPoint = syncPointTree.get(newEmptyPath());
    if (serverCache == null && syncPoint != null) {
      serverCache = syncPointGetCompleteServerCache(syncPoint, newEmptyPath());
    }
    let events2 = [];
    syncPointTree.children.inorderTraversal((childName, childTree) => {
      const childServerCache = serverCache ? serverCache.getImmediateChild(childName) : null;
      const childWritesCache = writeTreeRefChild(writesCache, childName);
      const childOperation = operation.operationForChild(childName);
      if (childOperation) {
        events2 = events2.concat(syncTreeApplyOperationDescendantsHelper_(childOperation, childTree, childServerCache, childWritesCache));
      }
    });
    if (syncPoint) {
      events2 = events2.concat(syncPointApplyOperation(syncPoint, operation, writesCache, serverCache));
    }
    return events2;
  }
  function syncTreeCreateListenerForView_(syncTree, view) {
    const query = view.query;
    const tag = syncTreeTagForQuery(syncTree, query);
    return {
      hashFn: () => {
        const cache = viewGetServerCache(view) || ChildrenNode.EMPTY_NODE;
        return cache.hash();
      },
      onComplete: (status) => {
        if (status === "ok") {
          if (tag) {
            return syncTreeApplyTaggedListenComplete(syncTree, query._path, tag);
          } else {
            return syncTreeApplyListenComplete(syncTree, query._path);
          }
        } else {
          const error2 = errorForServerCode(status, query);
          return syncTreeRemoveEventRegistration(
            syncTree,
            query,
            /*eventRegistration*/
            null,
            error2
          );
        }
      }
    };
  }
  function syncTreeTagForQuery(syncTree, query) {
    const queryKey = syncTreeMakeQueryKey_(query);
    return syncTree.queryToTagMap.get(queryKey);
  }
  function syncTreeMakeQueryKey_(query) {
    return query._path.toString() + "$" + query._queryIdentifier;
  }
  function syncTreeQueryKeyForTag_(syncTree, tag) {
    return syncTree.tagToQueryMap.get(tag);
  }
  function syncTreeParseQueryKey_(queryKey) {
    const splitIndex = queryKey.indexOf("$");
    assert(splitIndex !== -1 && splitIndex < queryKey.length - 1, "Bad queryKey.");
    return {
      queryId: queryKey.substr(splitIndex + 1),
      path: new Path(queryKey.substr(0, splitIndex))
    };
  }
  function syncTreeApplyTaggedOperation_(syncTree, queryPath, operation) {
    const syncPoint = syncTree.syncPointTree_.get(queryPath);
    assert(syncPoint, "Missing sync point for query tag that we're tracking");
    const writesCache = writeTreeChildWrites(syncTree.pendingWriteTree_, queryPath);
    return syncPointApplyOperation(syncPoint, operation, writesCache, null);
  }
  function syncTreeCollectDistinctViewsForSubTree_(subtree) {
    return subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
      if (maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
        const completeView = syncPointGetCompleteView(maybeChildSyncPoint);
        return [completeView];
      } else {
        let views = [];
        if (maybeChildSyncPoint) {
          views = syncPointGetQueryViews(maybeChildSyncPoint);
        }
        each(childMap, (_key, childViews) => {
          views = views.concat(childViews);
        });
        return views;
      }
    });
  }
  function syncTreeQueryForListening_(query) {
    if (query._queryParams.loadsAllData() && !query._queryParams.isDefault()) {
      return new (syncTreeGetReferenceConstructor())(query._repo, query._path);
    } else {
      return query;
    }
  }
  function syncTreeRemoveTags_(syncTree, queries) {
    for (let j2 = 0; j2 < queries.length; ++j2) {
      const removedQuery = queries[j2];
      if (!removedQuery._queryParams.loadsAllData()) {
        const removedQueryKey = syncTreeMakeQueryKey_(removedQuery);
        const removedQueryTag = syncTree.queryToTagMap.get(removedQueryKey);
        syncTree.queryToTagMap.delete(removedQueryKey);
        syncTree.tagToQueryMap.delete(removedQueryTag);
      }
    }
  }
  function syncTreeGetNextQueryTag_() {
    return syncTreeNextQueryTag_++;
  }
  function syncTreeSetupListener_(syncTree, query, view) {
    const path = query._path;
    const tag = syncTreeTagForQuery(syncTree, query);
    const listener = syncTreeCreateListenerForView_(syncTree, view);
    const events2 = syncTree.listenProvider_.startListening(syncTreeQueryForListening_(query), tag, listener.hashFn, listener.onComplete);
    const subtree = syncTree.syncPointTree_.subtree(path);
    if (tag) {
      assert(!syncPointHasCompleteView(subtree.value), "If we're adding a query, it shouldn't be shadowed");
    } else {
      const queriesToStop = subtree.fold((relativePath, maybeChildSyncPoint, childMap) => {
        if (!pathIsEmpty(relativePath) && maybeChildSyncPoint && syncPointHasCompleteView(maybeChildSyncPoint)) {
          return [syncPointGetCompleteView(maybeChildSyncPoint).query];
        } else {
          let queries = [];
          if (maybeChildSyncPoint) {
            queries = queries.concat(syncPointGetQueryViews(maybeChildSyncPoint).map((view2) => view2.query));
          }
          each(childMap, (_key, childQueries) => {
            queries = queries.concat(childQueries);
          });
          return queries;
        }
      });
      for (let i2 = 0; i2 < queriesToStop.length; ++i2) {
        const queryToStop = queriesToStop[i2];
        syncTree.listenProvider_.stopListening(syncTreeQueryForListening_(queryToStop), syncTreeTagForQuery(syncTree, queryToStop));
      }
    }
    return events2;
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class ExistingValueProvider {
    constructor(node_) {
      this.node_ = node_;
    }
    getImmediateChild(childName) {
      const child2 = this.node_.getImmediateChild(childName);
      return new ExistingValueProvider(child2);
    }
    node() {
      return this.node_;
    }
  }
  class DeferredValueProvider {
    constructor(syncTree, path) {
      this.syncTree_ = syncTree;
      this.path_ = path;
    }
    getImmediateChild(childName) {
      const childPath = pathChild(this.path_, childName);
      return new DeferredValueProvider(this.syncTree_, childPath);
    }
    node() {
      return syncTreeCalcCompleteEventCache(this.syncTree_, this.path_);
    }
  }
  const generateWithValues = function(values) {
    values = values || {};
    values["timestamp"] = values["timestamp"] || (/* @__PURE__ */ new Date()).getTime();
    return values;
  };
  const resolveDeferredLeafValue = function(value, existingVal, serverValues) {
    if (!value || typeof value !== "object") {
      return value;
    }
    assert(".sv" in value, "Unexpected leaf node or priority contents");
    if (typeof value[".sv"] === "string") {
      return resolveScalarDeferredValue(value[".sv"], existingVal, serverValues);
    } else if (typeof value[".sv"] === "object") {
      return resolveComplexDeferredValue(value[".sv"], existingVal);
    } else {
      assert(false, "Unexpected server value: " + JSON.stringify(value, null, 2));
    }
  };
  const resolveScalarDeferredValue = function(op, existing, serverValues) {
    switch (op) {
      case "timestamp":
        return serverValues["timestamp"];
      default:
        assert(false, "Unexpected server value: " + op);
    }
  };
  const resolveComplexDeferredValue = function(op, existing, unused) {
    if (!op.hasOwnProperty("increment")) {
      assert(false, "Unexpected server value: " + JSON.stringify(op, null, 2));
    }
    const delta = op["increment"];
    if (typeof delta !== "number") {
      assert(false, "Unexpected increment value: " + delta);
    }
    const existingNode = existing.node();
    assert(existingNode !== null && typeof existingNode !== "undefined", "Expected ChildrenNode.EMPTY_NODE for nulls");
    if (!existingNode.isLeafNode()) {
      return delta;
    }
    const leaf = existingNode;
    const existingVal = leaf.getValue();
    if (typeof existingVal !== "number") {
      return delta;
    }
    return existingVal + delta;
  };
  const resolveDeferredValueTree = function(path, node, syncTree, serverValues) {
    return resolveDeferredValue(node, new DeferredValueProvider(syncTree, path), serverValues);
  };
  const resolveDeferredValueSnapshot = function(node, existing, serverValues) {
    return resolveDeferredValue(node, new ExistingValueProvider(existing), serverValues);
  };
  function resolveDeferredValue(node, existingVal, serverValues) {
    const rawPri = node.getPriority().val();
    const priority = resolveDeferredLeafValue(rawPri, existingVal.getImmediateChild(".priority"), serverValues);
    let newNode;
    if (node.isLeafNode()) {
      const leafNode = node;
      const value = resolveDeferredLeafValue(leafNode.getValue(), existingVal, serverValues);
      if (value !== leafNode.getValue() || priority !== leafNode.getPriority().val()) {
        return new LeafNode(value, nodeFromJSON(priority));
      } else {
        return node;
      }
    } else {
      const childrenNode = node;
      newNode = childrenNode;
      if (priority !== childrenNode.getPriority().val()) {
        newNode = newNode.updatePriority(new LeafNode(priority));
      }
      childrenNode.forEachChild(PRIORITY_INDEX, (childName, childNode) => {
        const newChildNode = resolveDeferredValue(childNode, existingVal.getImmediateChild(childName), serverValues);
        if (newChildNode !== childNode) {
          newNode = newNode.updateImmediateChild(childName, newChildNode);
        }
      });
      return newNode;
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class Tree {
    /**
     * @param name - Optional name of the node.
     * @param parent - Optional parent node.
     * @param node - Optional node to wrap.
     */
    constructor(name2 = "", parent = null, node = { children: {}, childCount: 0 }) {
      this.name = name2;
      this.parent = parent;
      this.node = node;
    }
  }
  function treeSubTree(tree, pathObj) {
    let path = pathObj instanceof Path ? pathObj : new Path(pathObj);
    let child2 = tree, next = pathGetFront(path);
    while (next !== null) {
      const childNode = safeGet(child2.node.children, next) || {
        children: {},
        childCount: 0
      };
      child2 = new Tree(next, child2, childNode);
      path = pathPopFront(path);
      next = pathGetFront(path);
    }
    return child2;
  }
  function treeGetValue(tree) {
    return tree.node.value;
  }
  function treeSetValue(tree, value) {
    tree.node.value = value;
    treeUpdateParents(tree);
  }
  function treeHasChildren(tree) {
    return tree.node.childCount > 0;
  }
  function treeIsEmpty(tree) {
    return treeGetValue(tree) === void 0 && !treeHasChildren(tree);
  }
  function treeForEachChild(tree, action) {
    each(tree.node.children, (child2, childTree) => {
      action(new Tree(child2, tree, childTree));
    });
  }
  function treeForEachDescendant(tree, action, includeSelf, childrenFirst) {
    if (includeSelf && !childrenFirst) {
      action(tree);
    }
    treeForEachChild(tree, (child2) => {
      treeForEachDescendant(child2, action, true, childrenFirst);
    });
    if (includeSelf && childrenFirst) {
      action(tree);
    }
  }
  function treeForEachAncestor(tree, action, includeSelf) {
    let node = includeSelf ? tree : tree.parent;
    while (node !== null) {
      if (action(node)) {
        return true;
      }
      node = node.parent;
    }
    return false;
  }
  function treeGetPath(tree) {
    return new Path(tree.parent === null ? tree.name : treeGetPath(tree.parent) + "/" + tree.name);
  }
  function treeUpdateParents(tree) {
    if (tree.parent !== null) {
      treeUpdateChild(tree.parent, tree.name, tree);
    }
  }
  function treeUpdateChild(tree, childName, child2) {
    const childEmpty = treeIsEmpty(child2);
    const childExists = contains(tree.node.children, childName);
    if (childEmpty && childExists) {
      delete tree.node.children[childName];
      tree.node.childCount--;
      treeUpdateParents(tree);
    } else if (!childEmpty && !childExists) {
      tree.node.children[childName] = child2.node;
      tree.node.childCount++;
      treeUpdateParents(tree);
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const INVALID_KEY_REGEX_ = /[\[\].#$\/\u0000-\u001F\u007F]/;
  const INVALID_PATH_REGEX_ = /[\[\].#$\u0000-\u001F\u007F]/;
  const MAX_LEAF_SIZE_ = 10 * 1024 * 1024;
  const isValidKey = function(key) {
    return typeof key === "string" && key.length !== 0 && !INVALID_KEY_REGEX_.test(key);
  };
  const isValidPathString = function(pathString) {
    return typeof pathString === "string" && pathString.length !== 0 && !INVALID_PATH_REGEX_.test(pathString);
  };
  const isValidRootPathString = function(pathString) {
    if (pathString) {
      pathString = pathString.replace(/^\/*\.info(\/|$)/, "/");
    }
    return isValidPathString(pathString);
  };
  const validateFirebaseDataArg = function(fnName, value, path, optional) {
    if (optional && value === void 0) {
      return;
    }
    validateFirebaseData(errorPrefix(fnName, "value"), value, path);
  };
  const validateFirebaseData = function(errorPrefix2, data, path_) {
    const path = path_ instanceof Path ? new ValidationPath(path_, errorPrefix2) : path_;
    if (data === void 0) {
      throw new Error(errorPrefix2 + "contains undefined " + validationPathToErrorString(path));
    }
    if (typeof data === "function") {
      throw new Error(errorPrefix2 + "contains a function " + validationPathToErrorString(path) + " with contents = " + data.toString());
    }
    if (isInvalidJSONNumber(data)) {
      throw new Error(errorPrefix2 + "contains " + data.toString() + " " + validationPathToErrorString(path));
    }
    if (typeof data === "string" && data.length > MAX_LEAF_SIZE_ / 3 && stringLength(data) > MAX_LEAF_SIZE_) {
      throw new Error(errorPrefix2 + "contains a string greater than " + MAX_LEAF_SIZE_ + " utf8 bytes " + validationPathToErrorString(path) + " ('" + data.substring(0, 50) + "...')");
    }
    if (data && typeof data === "object") {
      let hasDotValue = false;
      let hasActualChild = false;
      each(data, (key, value) => {
        if (key === ".value") {
          hasDotValue = true;
        } else if (key !== ".priority" && key !== ".sv") {
          hasActualChild = true;
          if (!isValidKey(key)) {
            throw new Error(errorPrefix2 + " contains an invalid key (" + key + ") " + validationPathToErrorString(path) + `.  Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"`);
          }
        }
        validationPathPush(path, key);
        validateFirebaseData(errorPrefix2, value, path);
        validationPathPop(path);
      });
      if (hasDotValue && hasActualChild) {
        throw new Error(errorPrefix2 + ' contains ".value" child ' + validationPathToErrorString(path) + " in addition to actual children.");
      }
    }
  };
  const validatePathString = function(fnName, argumentName, pathString, optional) {
    if (optional && pathString === void 0) {
      return;
    }
    if (!isValidPathString(pathString)) {
      throw new Error(errorPrefix(fnName, argumentName) + 'was an invalid path = "' + pathString + `". Paths must be non-empty strings and can't contain ".", "#", "$", "[", or "]"`);
    }
  };
  const validateRootPathString = function(fnName, argumentName, pathString, optional) {
    if (pathString) {
      pathString = pathString.replace(/^\/*\.info(\/|$)/, "/");
    }
    validatePathString(fnName, argumentName, pathString, optional);
  };
  const validateWritablePath = function(fnName, path) {
    if (pathGetFront(path) === ".info") {
      throw new Error(fnName + " failed = Can't modify data under /.info/");
    }
  };
  const validateUrl = function(fnName, parsedUrl) {
    const pathString = parsedUrl.path.toString();
    if (!(typeof parsedUrl.repoInfo.host === "string") || parsedUrl.repoInfo.host.length === 0 || !isValidKey(parsedUrl.repoInfo.namespace) && parsedUrl.repoInfo.host.split(":")[0] !== "localhost" || pathString.length !== 0 && !isValidRootPathString(pathString)) {
      throw new Error(errorPrefix(fnName, "url") + `must be a valid firebase URL and the path can't contain ".", "#", "$", "[", or "]".`);
    }
  };
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class EventQueue {
    constructor() {
      this.eventLists_ = [];
      this.recursionDepth_ = 0;
    }
  }
  function eventQueueQueueEvents(eventQueue, eventDataList) {
    let currList = null;
    for (let i2 = 0; i2 < eventDataList.length; i2++) {
      const data = eventDataList[i2];
      const path = data.getPath();
      if (currList !== null && !pathEquals(path, currList.path)) {
        eventQueue.eventLists_.push(currList);
        currList = null;
      }
      if (currList === null) {
        currList = { events: [], path };
      }
      currList.events.push(data);
    }
    if (currList) {
      eventQueue.eventLists_.push(currList);
    }
  }
  function eventQueueRaiseEventsAtPath(eventQueue, path, eventDataList) {
    eventQueueQueueEvents(eventQueue, eventDataList);
    eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, (eventPath) => pathEquals(eventPath, path));
  }
  function eventQueueRaiseEventsForChangedPath(eventQueue, changedPath, eventDataList) {
    eventQueueQueueEvents(eventQueue, eventDataList);
    eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, (eventPath) => pathContains(eventPath, changedPath) || pathContains(changedPath, eventPath));
  }
  function eventQueueRaiseQueuedEventsMatchingPredicate(eventQueue, predicate) {
    eventQueue.recursionDepth_++;
    let sentAll = true;
    for (let i2 = 0; i2 < eventQueue.eventLists_.length; i2++) {
      const eventList = eventQueue.eventLists_[i2];
      if (eventList) {
        const eventPath = eventList.path;
        if (predicate(eventPath)) {
          eventListRaise(eventQueue.eventLists_[i2]);
          eventQueue.eventLists_[i2] = null;
        } else {
          sentAll = false;
        }
      }
    }
    if (sentAll) {
      eventQueue.eventLists_ = [];
    }
    eventQueue.recursionDepth_--;
  }
  function eventListRaise(eventList) {
    for (let i2 = 0; i2 < eventList.events.length; i2++) {
      const eventData = eventList.events[i2];
      if (eventData !== null) {
        eventList.events[i2] = null;
        const eventFn = eventData.getEventRunner();
        if (logger) {
          log("event: " + eventData.toString());
        }
        exceptionGuard(eventFn);
      }
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const INTERRUPT_REASON = "repo_interrupt";
  const MAX_TRANSACTION_RETRIES = 25;
  class Repo {
    constructor(repoInfo_, forceRestClient_, authTokenProvider_, appCheckProvider_) {
      this.repoInfo_ = repoInfo_;
      this.forceRestClient_ = forceRestClient_;
      this.authTokenProvider_ = authTokenProvider_;
      this.appCheckProvider_ = appCheckProvider_;
      this.dataUpdateCount = 0;
      this.statsListener_ = null;
      this.eventQueue_ = new EventQueue();
      this.nextWriteId_ = 1;
      this.interceptServerDataCallback_ = null;
      this.onDisconnect_ = newSparseSnapshotTree();
      this.transactionQueueTree_ = new Tree();
      this.persistentConnection_ = null;
      this.key = this.repoInfo_.toURLString();
    }
    /**
     * @returns The URL corresponding to the root of this Firebase.
     */
    toString() {
      return (this.repoInfo_.secure ? "https://" : "http://") + this.repoInfo_.host;
    }
  }
  function repoStart(repo, appId, authOverride) {
    repo.stats_ = statsManagerGetCollection(repo.repoInfo_);
    if (repo.forceRestClient_ || beingCrawled()) {
      repo.server_ = new ReadonlyRestClient(repo.repoInfo_, (pathString, data, isMerge, tag) => {
        repoOnDataUpdate(repo, pathString, data, isMerge, tag);
      }, repo.authTokenProvider_, repo.appCheckProvider_);
      setTimeout(() => repoOnConnectStatus(
        repo,
        /* connectStatus= */
        true
      ), 0);
    } else {
      if (typeof authOverride !== "undefined" && authOverride !== null) {
        if (typeof authOverride !== "object") {
          throw new Error("Only objects are supported for option databaseAuthVariableOverride");
        }
        try {
          stringify(authOverride);
        } catch (e2) {
          throw new Error("Invalid authOverride provided: " + e2);
        }
      }
      repo.persistentConnection_ = new PersistentConnection(repo.repoInfo_, appId, (pathString, data, isMerge, tag) => {
        repoOnDataUpdate(repo, pathString, data, isMerge, tag);
      }, (connectStatus) => {
        repoOnConnectStatus(repo, connectStatus);
      }, (updates) => {
        repoOnServerInfoUpdate(repo, updates);
      }, repo.authTokenProvider_, repo.appCheckProvider_, authOverride);
      repo.server_ = repo.persistentConnection_;
    }
    repo.authTokenProvider_.addTokenChangeListener((token) => {
      repo.server_.refreshAuthToken(token);
    });
    repo.appCheckProvider_.addTokenChangeListener((result) => {
      repo.server_.refreshAppCheckToken(result.token);
    });
    repo.statsReporter_ = statsManagerGetOrCreateReporter(repo.repoInfo_, () => new StatsReporter(repo.stats_, repo.server_));
    repo.infoData_ = new SnapshotHolder();
    repo.infoSyncTree_ = new SyncTree({
      startListening: (query, tag, currentHashFn, onComplete) => {
        let infoEvents = [];
        const node = repo.infoData_.getNode(query._path);
        if (!node.isEmpty()) {
          infoEvents = syncTreeApplyServerOverwrite(repo.infoSyncTree_, query._path, node);
          setTimeout(() => {
            onComplete("ok");
          }, 0);
        }
        return infoEvents;
      },
      stopListening: () => {
      }
    });
    repoUpdateInfo(repo, "connected", false);
    repo.serverSyncTree_ = new SyncTree({
      startListening: (query, tag, currentHashFn, onComplete) => {
        repo.server_.listen(query, currentHashFn, tag, (status, data) => {
          const events2 = onComplete(status, data);
          eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events2);
        });
        return [];
      },
      stopListening: (query, tag) => {
        repo.server_.unlisten(query, tag);
      }
    });
  }
  function repoServerTime(repo) {
    const offsetNode = repo.infoData_.getNode(new Path(".info/serverTimeOffset"));
    const offset = offsetNode.val() || 0;
    return (/* @__PURE__ */ new Date()).getTime() + offset;
  }
  function repoGenerateServerValues(repo) {
    return generateWithValues({
      timestamp: repoServerTime(repo)
    });
  }
  function repoOnDataUpdate(repo, pathString, data, isMerge, tag) {
    repo.dataUpdateCount++;
    const path = new Path(pathString);
    data = repo.interceptServerDataCallback_ ? repo.interceptServerDataCallback_(pathString, data) : data;
    let events2 = [];
    if (tag) {
      if (isMerge) {
        const taggedChildren = map(data, (raw) => nodeFromJSON(raw));
        events2 = syncTreeApplyTaggedQueryMerge(repo.serverSyncTree_, path, taggedChildren, tag);
      } else {
        const taggedSnap = nodeFromJSON(data);
        events2 = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, path, taggedSnap, tag);
      }
    } else if (isMerge) {
      const changedChildren = map(data, (raw) => nodeFromJSON(raw));
      events2 = syncTreeApplyServerMerge(repo.serverSyncTree_, path, changedChildren);
    } else {
      const snap = nodeFromJSON(data);
      events2 = syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap);
    }
    let affectedPath = path;
    if (events2.length > 0) {
      affectedPath = repoRerunTransactions(repo, path);
    }
    eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, events2);
  }
  function repoOnConnectStatus(repo, connectStatus) {
    repoUpdateInfo(repo, "connected", connectStatus);
    if (connectStatus === false) {
      repoRunOnDisconnectEvents(repo);
    }
  }
  function repoOnServerInfoUpdate(repo, updates) {
    each(updates, (key, value) => {
      repoUpdateInfo(repo, key, value);
    });
  }
  function repoUpdateInfo(repo, pathString, value) {
    const path = new Path("/.info/" + pathString);
    const newNode = nodeFromJSON(value);
    repo.infoData_.updateSnapshot(path, newNode);
    const events2 = syncTreeApplyServerOverwrite(repo.infoSyncTree_, path, newNode);
    eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events2);
  }
  function repoGetNextWriteId(repo) {
    return repo.nextWriteId_++;
  }
  function repoGetValue(repo, query, eventRegistration) {
    const cached = syncTreeGetServerValue(repo.serverSyncTree_, query);
    if (cached != null) {
      return Promise.resolve(cached);
    }
    return repo.server_.get(query).then((payload) => {
      const node = nodeFromJSON(payload).withIndex(query._queryParams.getIndex());
      syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration, true);
      let events2;
      if (query._queryParams.loadsAllData()) {
        events2 = syncTreeApplyServerOverwrite(repo.serverSyncTree_, query._path, node);
      } else {
        const tag = syncTreeTagForQuery(repo.serverSyncTree_, query);
        events2 = syncTreeApplyTaggedQueryOverwrite(repo.serverSyncTree_, query._path, node, tag);
      }
      eventQueueRaiseEventsForChangedPath(repo.eventQueue_, query._path, events2);
      syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration, null, true);
      return node;
    }, (err) => {
      repoLog(repo, "get for query " + stringify(query) + " failed: " + err);
      return Promise.reject(new Error(err));
    });
  }
  function repoSetWithPriority(repo, path, newVal, newPriority, onComplete) {
    repoLog(repo, "set", {
      path: path.toString(),
      value: newVal,
      priority: newPriority
    });
    const serverValues = repoGenerateServerValues(repo);
    const newNodeUnresolved = nodeFromJSON(newVal, newPriority);
    const existing = syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path);
    const newNode = resolveDeferredValueSnapshot(newNodeUnresolved, existing, serverValues);
    const writeId = repoGetNextWriteId(repo);
    const events2 = syncTreeApplyUserOverwrite(repo.serverSyncTree_, path, newNode, writeId, true);
    eventQueueQueueEvents(repo.eventQueue_, events2);
    repo.server_.put(path.toString(), newNodeUnresolved.val(
      /*export=*/
      true
    ), (status, errorReason) => {
      const success = status === "ok";
      if (!success) {
        warn("set at " + path + " failed: " + status);
      }
      const clearEvents = syncTreeAckUserWrite(repo.serverSyncTree_, writeId, !success);
      eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, clearEvents);
      repoCallOnCompleteCallback(repo, onComplete, status, errorReason);
    });
    const affectedPath = repoAbortTransactions(repo, path);
    repoRerunTransactions(repo, affectedPath);
    eventQueueRaiseEventsForChangedPath(repo.eventQueue_, affectedPath, []);
  }
  function repoRunOnDisconnectEvents(repo) {
    repoLog(repo, "onDisconnectEvents");
    const serverValues = repoGenerateServerValues(repo);
    const resolvedOnDisconnectTree = newSparseSnapshotTree();
    sparseSnapshotTreeForEachTree(repo.onDisconnect_, newEmptyPath(), (path, node) => {
      const resolved = resolveDeferredValueTree(path, node, repo.serverSyncTree_, serverValues);
      sparseSnapshotTreeRemember(resolvedOnDisconnectTree, path, resolved);
    });
    let events2 = [];
    sparseSnapshotTreeForEachTree(resolvedOnDisconnectTree, newEmptyPath(), (path, snap) => {
      events2 = events2.concat(syncTreeApplyServerOverwrite(repo.serverSyncTree_, path, snap));
      const affectedPath = repoAbortTransactions(repo, path);
      repoRerunTransactions(repo, affectedPath);
    });
    repo.onDisconnect_ = newSparseSnapshotTree();
    eventQueueRaiseEventsForChangedPath(repo.eventQueue_, newEmptyPath(), events2);
  }
  function repoAddEventCallbackForQuery(repo, query, eventRegistration) {
    let events2;
    if (pathGetFront(query._path) === ".info") {
      events2 = syncTreeAddEventRegistration(repo.infoSyncTree_, query, eventRegistration);
    } else {
      events2 = syncTreeAddEventRegistration(repo.serverSyncTree_, query, eventRegistration);
    }
    eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events2);
  }
  function repoRemoveEventCallbackForQuery(repo, query, eventRegistration) {
    let events2;
    if (pathGetFront(query._path) === ".info") {
      events2 = syncTreeRemoveEventRegistration(repo.infoSyncTree_, query, eventRegistration);
    } else {
      events2 = syncTreeRemoveEventRegistration(repo.serverSyncTree_, query, eventRegistration);
    }
    eventQueueRaiseEventsAtPath(repo.eventQueue_, query._path, events2);
  }
  function repoInterrupt(repo) {
    if (repo.persistentConnection_) {
      repo.persistentConnection_.interrupt(INTERRUPT_REASON);
    }
  }
  function repoLog(repo, ...varArgs) {
    let prefix = "";
    if (repo.persistentConnection_) {
      prefix = repo.persistentConnection_.id + ":";
    }
    log(prefix, ...varArgs);
  }
  function repoCallOnCompleteCallback(repo, callback, status, errorReason) {
    if (callback) {
      exceptionGuard(() => {
        if (status === "ok") {
          callback(null);
        } else {
          const code = (status || "error").toUpperCase();
          let message = code;
          if (errorReason) {
            message += ": " + errorReason;
          }
          const error2 = new Error(message);
          error2.code = code;
          callback(error2);
        }
      });
    }
  }
  function repoGetLatestState(repo, path, excludeSets) {
    return syncTreeCalcCompleteEventCache(repo.serverSyncTree_, path, excludeSets) || ChildrenNode.EMPTY_NODE;
  }
  function repoSendReadyTransactions(repo, node = repo.transactionQueueTree_) {
    if (!node) {
      repoPruneCompletedTransactionsBelowNode(repo, node);
    }
    if (treeGetValue(node)) {
      const queue = repoBuildTransactionQueue(repo, node);
      assert(queue.length > 0, "Sending zero length transaction queue");
      const allRun = queue.every(
        (transaction) => transaction.status === 0
        /* TransactionStatus.RUN */
      );
      if (allRun) {
        repoSendTransactionQueue(repo, treeGetPath(node), queue);
      }
    } else if (treeHasChildren(node)) {
      treeForEachChild(node, (childNode) => {
        repoSendReadyTransactions(repo, childNode);
      });
    }
  }
  function repoSendTransactionQueue(repo, path, queue) {
    const setsToIgnore = queue.map((txn) => {
      return txn.currentWriteId;
    });
    const latestState = repoGetLatestState(repo, path, setsToIgnore);
    let snapToSend = latestState;
    const latestHash = latestState.hash();
    for (let i2 = 0; i2 < queue.length; i2++) {
      const txn = queue[i2];
      assert(txn.status === 0, "tryToSendTransactionQueue_: items in queue should all be run.");
      txn.status = 1;
      txn.retryCount++;
      const relativePath = newRelativePath(path, txn.path);
      snapToSend = snapToSend.updateChild(relativePath, txn.currentOutputSnapshotRaw);
    }
    const dataToSend = snapToSend.val(true);
    const pathToSend = path;
    repo.server_.put(pathToSend.toString(), dataToSend, (status) => {
      repoLog(repo, "transaction put response", {
        path: pathToSend.toString(),
        status
      });
      let events2 = [];
      if (status === "ok") {
        const callbacks = [];
        for (let i2 = 0; i2 < queue.length; i2++) {
          queue[i2].status = 2;
          events2 = events2.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i2].currentWriteId));
          if (queue[i2].onComplete) {
            callbacks.push(() => queue[i2].onComplete(null, true, queue[i2].currentOutputSnapshotResolved));
          }
          queue[i2].unwatcher();
        }
        repoPruneCompletedTransactionsBelowNode(repo, treeSubTree(repo.transactionQueueTree_, path));
        repoSendReadyTransactions(repo, repo.transactionQueueTree_);
        eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events2);
        for (let i2 = 0; i2 < callbacks.length; i2++) {
          exceptionGuard(callbacks[i2]);
        }
      } else {
        if (status === "datastale") {
          for (let i2 = 0; i2 < queue.length; i2++) {
            if (queue[i2].status === 3) {
              queue[i2].status = 4;
            } else {
              queue[i2].status = 0;
            }
          }
        } else {
          warn("transaction at " + pathToSend.toString() + " failed: " + status);
          for (let i2 = 0; i2 < queue.length; i2++) {
            queue[i2].status = 4;
            queue[i2].abortReason = status;
          }
        }
        repoRerunTransactions(repo, path);
      }
    }, latestHash);
  }
  function repoRerunTransactions(repo, changedPath) {
    const rootMostTransactionNode = repoGetAncestorTransactionNode(repo, changedPath);
    const path = treeGetPath(rootMostTransactionNode);
    const queue = repoBuildTransactionQueue(repo, rootMostTransactionNode);
    repoRerunTransactionQueue(repo, queue, path);
    return path;
  }
  function repoRerunTransactionQueue(repo, queue, path) {
    if (queue.length === 0) {
      return;
    }
    const callbacks = [];
    let events2 = [];
    const txnsToRerun = queue.filter((q2) => {
      return q2.status === 0;
    });
    const setsToIgnore = txnsToRerun.map((q2) => {
      return q2.currentWriteId;
    });
    for (let i2 = 0; i2 < queue.length; i2++) {
      const transaction = queue[i2];
      const relativePath = newRelativePath(path, transaction.path);
      let abortTransaction = false, abortReason;
      assert(relativePath !== null, "rerunTransactionsUnderNode_: relativePath should not be null.");
      if (transaction.status === 4) {
        abortTransaction = true;
        abortReason = transaction.abortReason;
        events2 = events2.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
      } else if (transaction.status === 0) {
        if (transaction.retryCount >= MAX_TRANSACTION_RETRIES) {
          abortTransaction = true;
          abortReason = "maxretry";
          events2 = events2.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
        } else {
          const currentNode = repoGetLatestState(repo, transaction.path, setsToIgnore);
          transaction.currentInputSnapshot = currentNode;
          const newData = queue[i2].update(currentNode.val());
          if (newData !== void 0) {
            validateFirebaseData("transaction failed: Data returned ", newData, transaction.path);
            let newDataNode = nodeFromJSON(newData);
            const hasExplicitPriority = typeof newData === "object" && newData != null && contains(newData, ".priority");
            if (!hasExplicitPriority) {
              newDataNode = newDataNode.updatePriority(currentNode.getPriority());
            }
            const oldWriteId = transaction.currentWriteId;
            const serverValues = repoGenerateServerValues(repo);
            const newNodeResolved = resolveDeferredValueSnapshot(newDataNode, currentNode, serverValues);
            transaction.currentOutputSnapshotRaw = newDataNode;
            transaction.currentOutputSnapshotResolved = newNodeResolved;
            transaction.currentWriteId = repoGetNextWriteId(repo);
            setsToIgnore.splice(setsToIgnore.indexOf(oldWriteId), 1);
            events2 = events2.concat(syncTreeApplyUserOverwrite(repo.serverSyncTree_, transaction.path, newNodeResolved, transaction.currentWriteId, transaction.applyLocally));
            events2 = events2.concat(syncTreeAckUserWrite(repo.serverSyncTree_, oldWriteId, true));
          } else {
            abortTransaction = true;
            abortReason = "nodata";
            events2 = events2.concat(syncTreeAckUserWrite(repo.serverSyncTree_, transaction.currentWriteId, true));
          }
        }
      }
      eventQueueRaiseEventsForChangedPath(repo.eventQueue_, path, events2);
      events2 = [];
      if (abortTransaction) {
        queue[i2].status = 2;
        (function(unwatcher) {
          setTimeout(unwatcher, Math.floor(0));
        })(queue[i2].unwatcher);
        if (queue[i2].onComplete) {
          if (abortReason === "nodata") {
            callbacks.push(() => queue[i2].onComplete(null, false, queue[i2].currentInputSnapshot));
          } else {
            callbacks.push(() => queue[i2].onComplete(new Error(abortReason), false, null));
          }
        }
      }
    }
    repoPruneCompletedTransactionsBelowNode(repo, repo.transactionQueueTree_);
    for (let i2 = 0; i2 < callbacks.length; i2++) {
      exceptionGuard(callbacks[i2]);
    }
    repoSendReadyTransactions(repo, repo.transactionQueueTree_);
  }
  function repoGetAncestorTransactionNode(repo, path) {
    let front;
    let transactionNode = repo.transactionQueueTree_;
    front = pathGetFront(path);
    while (front !== null && treeGetValue(transactionNode) === void 0) {
      transactionNode = treeSubTree(transactionNode, front);
      path = pathPopFront(path);
      front = pathGetFront(path);
    }
    return transactionNode;
  }
  function repoBuildTransactionQueue(repo, transactionNode) {
    const transactionQueue = [];
    repoAggregateTransactionQueuesForNode(repo, transactionNode, transactionQueue);
    transactionQueue.sort((a2, b2) => a2.order - b2.order);
    return transactionQueue;
  }
  function repoAggregateTransactionQueuesForNode(repo, node, queue) {
    const nodeQueue = treeGetValue(node);
    if (nodeQueue) {
      for (let i2 = 0; i2 < nodeQueue.length; i2++) {
        queue.push(nodeQueue[i2]);
      }
    }
    treeForEachChild(node, (child2) => {
      repoAggregateTransactionQueuesForNode(repo, child2, queue);
    });
  }
  function repoPruneCompletedTransactionsBelowNode(repo, node) {
    const queue = treeGetValue(node);
    if (queue) {
      let to = 0;
      for (let from = 0; from < queue.length; from++) {
        if (queue[from].status !== 2) {
          queue[to] = queue[from];
          to++;
        }
      }
      queue.length = to;
      treeSetValue(node, queue.length > 0 ? queue : void 0);
    }
    treeForEachChild(node, (childNode) => {
      repoPruneCompletedTransactionsBelowNode(repo, childNode);
    });
  }
  function repoAbortTransactions(repo, path) {
    const affectedPath = treeGetPath(repoGetAncestorTransactionNode(repo, path));
    const transactionNode = treeSubTree(repo.transactionQueueTree_, path);
    treeForEachAncestor(transactionNode, (node) => {
      repoAbortTransactionsOnNode(repo, node);
    });
    repoAbortTransactionsOnNode(repo, transactionNode);
    treeForEachDescendant(transactionNode, (node) => {
      repoAbortTransactionsOnNode(repo, node);
    });
    return affectedPath;
  }
  function repoAbortTransactionsOnNode(repo, node) {
    const queue = treeGetValue(node);
    if (queue) {
      const callbacks = [];
      let events2 = [];
      let lastSent = -1;
      for (let i2 = 0; i2 < queue.length; i2++) {
        if (queue[i2].status === 3)
          ;
        else if (queue[i2].status === 1) {
          assert(lastSent === i2 - 1, "All SENT items should be at beginning of queue.");
          lastSent = i2;
          queue[i2].status = 3;
          queue[i2].abortReason = "set";
        } else {
          assert(queue[i2].status === 0, "Unexpected transaction status in abort");
          queue[i2].unwatcher();
          events2 = events2.concat(syncTreeAckUserWrite(repo.serverSyncTree_, queue[i2].currentWriteId, true));
          if (queue[i2].onComplete) {
            callbacks.push(queue[i2].onComplete.bind(null, new Error("set"), false, null));
          }
        }
      }
      if (lastSent === -1) {
        treeSetValue(node, void 0);
      } else {
        queue.length = lastSent + 1;
      }
      eventQueueRaiseEventsForChangedPath(repo.eventQueue_, treeGetPath(node), events2);
      for (let i2 = 0; i2 < callbacks.length; i2++) {
        exceptionGuard(callbacks[i2]);
      }
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function decodePath(pathString) {
    let pathStringDecoded = "";
    const pieces = pathString.split("/");
    for (let i2 = 0; i2 < pieces.length; i2++) {
      if (pieces[i2].length > 0) {
        let piece = pieces[i2];
        try {
          piece = decodeURIComponent(piece.replace(/\+/g, " "));
        } catch (e2) {
        }
        pathStringDecoded += "/" + piece;
      }
    }
    return pathStringDecoded;
  }
  function decodeQuery(queryString) {
    const results = {};
    if (queryString.charAt(0) === "?") {
      queryString = queryString.substring(1);
    }
    for (const segment of queryString.split("&")) {
      if (segment.length === 0) {
        continue;
      }
      const kv = segment.split("=");
      if (kv.length === 2) {
        results[decodeURIComponent(kv[0])] = decodeURIComponent(kv[1]);
      } else {
        warn(`Invalid query segment '${segment}' in query '${queryString}'`);
      }
    }
    return results;
  }
  const parseRepoInfo = function(dataURL, nodeAdmin) {
    const parsedUrl = parseDatabaseURL(dataURL), namespace = parsedUrl.namespace;
    if (parsedUrl.domain === "firebase.com") {
      fatal(parsedUrl.host + " is no longer supported. Please use <YOUR FIREBASE>.firebaseio.com instead");
    }
    if ((!namespace || namespace === "undefined") && parsedUrl.domain !== "localhost") {
      fatal("Cannot parse Firebase url. Please use https://<YOUR FIREBASE>.firebaseio.com");
    }
    if (!parsedUrl.secure) {
      warnIfPageIsSecure();
    }
    const webSocketOnly = parsedUrl.scheme === "ws" || parsedUrl.scheme === "wss";
    return {
      repoInfo: new RepoInfo(
        parsedUrl.host,
        parsedUrl.secure,
        namespace,
        webSocketOnly,
        nodeAdmin,
        /*persistenceKey=*/
        "",
        /*includeNamespaceInQueryParams=*/
        namespace !== parsedUrl.subdomain
      ),
      path: new Path(parsedUrl.pathString)
    };
  };
  const parseDatabaseURL = function(dataURL) {
    let host = "", domain = "", subdomain = "", pathString = "", namespace = "";
    let secure = true, scheme = "https", port = 443;
    if (typeof dataURL === "string") {
      let colonInd = dataURL.indexOf("//");
      if (colonInd >= 0) {
        scheme = dataURL.substring(0, colonInd - 1);
        dataURL = dataURL.substring(colonInd + 2);
      }
      let slashInd = dataURL.indexOf("/");
      if (slashInd === -1) {
        slashInd = dataURL.length;
      }
      let questionMarkInd = dataURL.indexOf("?");
      if (questionMarkInd === -1) {
        questionMarkInd = dataURL.length;
      }
      host = dataURL.substring(0, Math.min(slashInd, questionMarkInd));
      if (slashInd < questionMarkInd) {
        pathString = decodePath(dataURL.substring(slashInd, questionMarkInd));
      }
      const queryParams = decodeQuery(dataURL.substring(Math.min(dataURL.length, questionMarkInd)));
      colonInd = host.indexOf(":");
      if (colonInd >= 0) {
        secure = scheme === "https" || scheme === "wss";
        port = parseInt(host.substring(colonInd + 1), 10);
      } else {
        colonInd = host.length;
      }
      const hostWithoutPort = host.slice(0, colonInd);
      if (hostWithoutPort.toLowerCase() === "localhost") {
        domain = "localhost";
      } else if (hostWithoutPort.split(".").length <= 2) {
        domain = hostWithoutPort;
      } else {
        const dotInd = host.indexOf(".");
        subdomain = host.substring(0, dotInd).toLowerCase();
        domain = host.substring(dotInd + 1);
        namespace = subdomain;
      }
      if ("ns" in queryParams) {
        namespace = queryParams["ns"];
      }
    }
    return {
      host,
      port,
      domain,
      subdomain,
      secure,
      scheme,
      pathString,
      namespace
    };
  };
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class DataEvent {
    /**
     * @param eventType - One of: value, child_added, child_changed, child_moved, child_removed
     * @param eventRegistration - The function to call to with the event data. User provided
     * @param snapshot - The data backing the event
     * @param prevName - Optional, the name of the previous child for child_* events.
     */
    constructor(eventType, eventRegistration, snapshot, prevName) {
      this.eventType = eventType;
      this.eventRegistration = eventRegistration;
      this.snapshot = snapshot;
      this.prevName = prevName;
    }
    getPath() {
      const ref2 = this.snapshot.ref;
      if (this.eventType === "value") {
        return ref2._path;
      } else {
        return ref2.parent._path;
      }
    }
    getEventType() {
      return this.eventType;
    }
    getEventRunner() {
      return this.eventRegistration.getEventRunner(this);
    }
    toString() {
      return this.getPath().toString() + ":" + this.eventType + ":" + stringify(this.snapshot.exportVal());
    }
  }
  class CancelEvent {
    constructor(eventRegistration, error2, path) {
      this.eventRegistration = eventRegistration;
      this.error = error2;
      this.path = path;
    }
    getPath() {
      return this.path;
    }
    getEventType() {
      return "cancel";
    }
    getEventRunner() {
      return this.eventRegistration.getEventRunner(this);
    }
    toString() {
      return this.path.toString() + ":cancel";
    }
  }
  /**
   * @license
   * Copyright 2017 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class CallbackContext {
    constructor(snapshotCallback, cancelCallback) {
      this.snapshotCallback = snapshotCallback;
      this.cancelCallback = cancelCallback;
    }
    onValue(expDataSnapshot, previousChildName) {
      this.snapshotCallback.call(null, expDataSnapshot, previousChildName);
    }
    onCancel(error2) {
      assert(this.hasCancelCallback, "Raising a cancel event on a listener with no cancel callback");
      return this.cancelCallback.call(null, error2);
    }
    get hasCancelCallback() {
      return !!this.cancelCallback;
    }
    matches(other) {
      return this.snapshotCallback === other.snapshotCallback || this.snapshotCallback.userCallback !== void 0 && this.snapshotCallback.userCallback === other.snapshotCallback.userCallback && this.snapshotCallback.context === other.snapshotCallback.context;
    }
  }
  /**
   * @license
   * Copyright 2020 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  class QueryImpl {
    /**
     * @hideconstructor
     */
    constructor(_repo, _path, _queryParams, _orderByCalled) {
      this._repo = _repo;
      this._path = _path;
      this._queryParams = _queryParams;
      this._orderByCalled = _orderByCalled;
    }
    get key() {
      if (pathIsEmpty(this._path)) {
        return null;
      } else {
        return pathGetBack(this._path);
      }
    }
    get ref() {
      return new ReferenceImpl(this._repo, this._path);
    }
    get _queryIdentifier() {
      const obj = queryParamsGetQueryObject(this._queryParams);
      const id = ObjectToUniqueKey(obj);
      return id === "{}" ? "default" : id;
    }
    /**
     * An object representation of the query parameters used by this Query.
     */
    get _queryObject() {
      return queryParamsGetQueryObject(this._queryParams);
    }
    isEqual(other) {
      other = getModularInstance(other);
      if (!(other instanceof QueryImpl)) {
        return false;
      }
      const sameRepo = this._repo === other._repo;
      const samePath = pathEquals(this._path, other._path);
      const sameQueryIdentifier = this._queryIdentifier === other._queryIdentifier;
      return sameRepo && samePath && sameQueryIdentifier;
    }
    toJSON() {
      return this.toString();
    }
    toString() {
      return this._repo.toString() + pathToUrlEncodedString(this._path);
    }
  }
  class ReferenceImpl extends QueryImpl {
    /** @hideconstructor */
    constructor(repo, path) {
      super(repo, path, new QueryParams(), false);
    }
    get parent() {
      const parentPath = pathParent(this._path);
      return parentPath === null ? null : new ReferenceImpl(this._repo, parentPath);
    }
    get root() {
      let ref2 = this;
      while (ref2.parent !== null) {
        ref2 = ref2.parent;
      }
      return ref2;
    }
  }
  class DataSnapshot {
    /**
     * @param _node - A SnapshotNode to wrap.
     * @param ref - The location this snapshot came from.
     * @param _index - The iteration order for this snapshot
     * @hideconstructor
     */
    constructor(_node, ref2, _index) {
      this._node = _node;
      this.ref = ref2;
      this._index = _index;
    }
    /**
     * Gets the priority value of the data in this `DataSnapshot`.
     *
     * Applications need not use priority but can order collections by
     * ordinary properties (see
     * {@link https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data |Sorting and filtering data}
     * ).
     */
    get priority() {
      return this._node.getPriority().val();
    }
    /**
     * The key (last part of the path) of the location of this `DataSnapshot`.
     *
     * The last token in a Database location is considered its key. For example,
     * "ada" is the key for the /users/ada/ node. Accessing the key on any
     * `DataSnapshot` will return the key for the location that generated it.
     * However, accessing the key on the root URL of a Database will return
     * `null`.
     */
    get key() {
      return this.ref.key;
    }
    /** Returns the number of child properties of this `DataSnapshot`. */
    get size() {
      return this._node.numChildren();
    }
    /**
     * Gets another `DataSnapshot` for the location at the specified relative path.
     *
     * Passing a relative path to the `child()` method of a DataSnapshot returns
     * another `DataSnapshot` for the location at the specified relative path. The
     * relative path can either be a simple child name (for example, "ada") or a
     * deeper, slash-separated path (for example, "ada/name/first"). If the child
     * location has no data, an empty `DataSnapshot` (that is, a `DataSnapshot`
     * whose value is `null`) is returned.
     *
     * @param path - A relative path to the location of child data.
     */
    child(path) {
      const childPath = new Path(path);
      const childRef = child(this.ref, path);
      return new DataSnapshot(this._node.getChild(childPath), childRef, PRIORITY_INDEX);
    }
    /**
     * Returns true if this `DataSnapshot` contains any data. It is slightly more
     * efficient than using `snapshot.val() !== null`.
     */
    exists() {
      return !this._node.isEmpty();
    }
    /**
     * Exports the entire contents of the DataSnapshot as a JavaScript object.
     *
     * The `exportVal()` method is similar to `val()`, except priority information
     * is included (if available), making it suitable for backing up your data.
     *
     * @returns The DataSnapshot's contents as a JavaScript value (Object,
     *   Array, string, number, boolean, or `null`).
     */
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    exportVal() {
      return this._node.val(true);
    }
    /**
     * Enumerates the top-level children in the `IteratedDataSnapshot`.
     *
     * Because of the way JavaScript objects work, the ordering of data in the
     * JavaScript object returned by `val()` is not guaranteed to match the
     * ordering on the server nor the ordering of `onChildAdded()` events. That is
     * where `forEach()` comes in handy. It guarantees the children of a
     * `DataSnapshot` will be iterated in their query order.
     *
     * If no explicit `orderBy*()` method is used, results are returned
     * ordered by key (unless priorities are used, in which case, results are
     * returned by priority).
     *
     * @param action - A function that will be called for each child DataSnapshot.
     * The callback can return true to cancel further enumeration.
     * @returns true if enumeration was canceled due to your callback returning
     * true.
     */
    forEach(action) {
      if (this._node.isLeafNode()) {
        return false;
      }
      const childrenNode = this._node;
      return !!childrenNode.forEachChild(this._index, (key, node) => {
        return action(new DataSnapshot(node, child(this.ref, key), PRIORITY_INDEX));
      });
    }
    /**
     * Returns true if the specified child path has (non-null) data.
     *
     * @param path - A relative path to the location of a potential child.
     * @returns `true` if data exists at the specified child path; else
     *  `false`.
     */
    hasChild(path) {
      const childPath = new Path(path);
      return !this._node.getChild(childPath).isEmpty();
    }
    /**
     * Returns whether or not the `DataSnapshot` has any non-`null` child
     * properties.
     *
     * You can use `hasChildren()` to determine if a `DataSnapshot` has any
     * children. If it does, you can enumerate them using `forEach()`. If it
     * doesn't, then either this snapshot contains a primitive value (which can be
     * retrieved with `val()`) or it is empty (in which case, `val()` will return
     * `null`).
     *
     * @returns true if this snapshot has any children; else false.
     */
    hasChildren() {
      if (this._node.isLeafNode()) {
        return false;
      } else {
        return !this._node.isEmpty();
      }
    }
    /**
     * Returns a JSON-serializable representation of this object.
     */
    toJSON() {
      return this.exportVal();
    }
    /**
     * Extracts a JavaScript value from a `DataSnapshot`.
     *
     * Depending on the data in a `DataSnapshot`, the `val()` method may return a
     * scalar type (string, number, or boolean), an array, or an object. It may
     * also return null, indicating that the `DataSnapshot` is empty (contains no
     * data).
     *
     * @returns The DataSnapshot's contents as a JavaScript value (Object,
     *   Array, string, number, boolean, or `null`).
     */
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    val() {
      return this._node.val();
    }
  }
  function ref(db, path) {
    db = getModularInstance(db);
    db._checkNotDeleted("ref");
    return path !== void 0 ? child(db._root, path) : db._root;
  }
  function child(parent, path) {
    parent = getModularInstance(parent);
    if (pathGetFront(parent._path) === null) {
      validateRootPathString("child", "path", path, false);
    } else {
      validatePathString("child", "path", path, false);
    }
    return new ReferenceImpl(parent._repo, pathChild(parent._path, path));
  }
  function set(ref2, value) {
    ref2 = getModularInstance(ref2);
    validateWritablePath("set", ref2._path);
    validateFirebaseDataArg("set", value, ref2._path, false);
    const deferred = new Deferred();
    repoSetWithPriority(
      ref2._repo,
      ref2._path,
      value,
      /*priority=*/
      null,
      deferred.wrapCallback(() => {
      })
    );
    return deferred.promise;
  }
  function get(query) {
    query = getModularInstance(query);
    const callbackContext = new CallbackContext(() => {
    });
    const container = new ValueEventRegistration(callbackContext);
    return repoGetValue(query._repo, query, container).then((node) => {
      return new DataSnapshot(node, new ReferenceImpl(query._repo, query._path), query._queryParams.getIndex());
    });
  }
  class ValueEventRegistration {
    constructor(callbackContext) {
      this.callbackContext = callbackContext;
    }
    respondsTo(eventType) {
      return eventType === "value";
    }
    createEvent(change, query) {
      const index2 = query._queryParams.getIndex();
      return new DataEvent("value", this, new DataSnapshot(change.snapshotNode, new ReferenceImpl(query._repo, query._path), index2));
    }
    getEventRunner(eventData) {
      if (eventData.getEventType() === "cancel") {
        return () => this.callbackContext.onCancel(eventData.error);
      } else {
        return () => this.callbackContext.onValue(eventData.snapshot, null);
      }
    }
    createCancelEvent(error2, path) {
      if (this.callbackContext.hasCancelCallback) {
        return new CancelEvent(this, error2, path);
      } else {
        return null;
      }
    }
    matches(other) {
      if (!(other instanceof ValueEventRegistration)) {
        return false;
      } else if (!other.callbackContext || !this.callbackContext) {
        return true;
      } else {
        return other.callbackContext.matches(this.callbackContext);
      }
    }
    hasAnyCallback() {
      return this.callbackContext !== null;
    }
  }
  class ChildEventRegistration {
    constructor(eventType, callbackContext) {
      this.eventType = eventType;
      this.callbackContext = callbackContext;
    }
    respondsTo(eventType) {
      let eventToCheck = eventType === "children_added" ? "child_added" : eventType;
      eventToCheck = eventToCheck === "children_removed" ? "child_removed" : eventToCheck;
      return this.eventType === eventToCheck;
    }
    createCancelEvent(error2, path) {
      if (this.callbackContext.hasCancelCallback) {
        return new CancelEvent(this, error2, path);
      } else {
        return null;
      }
    }
    createEvent(change, query) {
      assert(change.childName != null, "Child events should have a childName.");
      const childRef = child(new ReferenceImpl(query._repo, query._path), change.childName);
      const index2 = query._queryParams.getIndex();
      return new DataEvent(change.type, this, new DataSnapshot(change.snapshotNode, childRef, index2), change.prevName);
    }
    getEventRunner(eventData) {
      if (eventData.getEventType() === "cancel") {
        return () => this.callbackContext.onCancel(eventData.error);
      } else {
        return () => this.callbackContext.onValue(eventData.snapshot, eventData.prevName);
      }
    }
    matches(other) {
      if (other instanceof ChildEventRegistration) {
        return this.eventType === other.eventType && (!this.callbackContext || !other.callbackContext || this.callbackContext.matches(other.callbackContext));
      }
      return false;
    }
    hasAnyCallback() {
      return !!this.callbackContext;
    }
  }
  function addEventListener$1(query, eventType, callback, cancelCallbackOrListenOptions, options) {
    let cancelCallback;
    if (typeof cancelCallbackOrListenOptions === "object") {
      cancelCallback = void 0;
      options = cancelCallbackOrListenOptions;
    }
    if (typeof cancelCallbackOrListenOptions === "function") {
      cancelCallback = cancelCallbackOrListenOptions;
    }
    if (options && options.onlyOnce) {
      const userCallback = callback;
      const onceCallback = (dataSnapshot, previousChildName) => {
        repoRemoveEventCallbackForQuery(query._repo, query, container);
        userCallback(dataSnapshot, previousChildName);
      };
      onceCallback.userCallback = callback.userCallback;
      onceCallback.context = callback.context;
      callback = onceCallback;
    }
    const callbackContext = new CallbackContext(callback, cancelCallback || void 0);
    const container = eventType === "value" ? new ValueEventRegistration(callbackContext) : new ChildEventRegistration(eventType, callbackContext);
    repoAddEventCallbackForQuery(query._repo, query, container);
    return () => repoRemoveEventCallbackForQuery(query._repo, query, container);
  }
  function onValue(query, callback, cancelCallbackOrListenOptions, options) {
    return addEventListener$1(query, "value", callback, cancelCallbackOrListenOptions, options);
  }
  syncPointSetReferenceConstructor(ReferenceImpl);
  syncTreeSetReferenceConstructor(ReferenceImpl);
  /**
   * @license
   * Copyright 2020 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  const FIREBASE_DATABASE_EMULATOR_HOST_VAR = "FIREBASE_DATABASE_EMULATOR_HOST";
  const repos = {};
  let useRestClient = false;
  function repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider) {
    repo.repoInfo_ = new RepoInfo(
      `${host}:${port}`,
      /* secure= */
      false,
      repo.repoInfo_.namespace,
      repo.repoInfo_.webSocketOnly,
      repo.repoInfo_.nodeAdmin,
      repo.repoInfo_.persistenceKey,
      repo.repoInfo_.includeNamespaceInQueryParams,
      /*isUsingEmulator=*/
      true
    );
    if (tokenProvider) {
      repo.authTokenProvider_ = tokenProvider;
    }
  }
  function repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url, nodeAdmin) {
    let dbUrl = url || app.options.databaseURL;
    if (dbUrl === void 0) {
      if (!app.options.projectId) {
        fatal("Can't determine Firebase Database URL. Be sure to include  a Project ID when calling firebase.initializeApp().");
      }
      log("Using default host for project ", app.options.projectId);
      dbUrl = `${app.options.projectId}-default-rtdb.firebaseio.com`;
    }
    let parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
    let repoInfo = parsedUrl.repoInfo;
    let isEmulator;
    let dbEmulatorHost = void 0;
    if (typeof process !== "undefined" && process.env) {
      dbEmulatorHost = process.env[FIREBASE_DATABASE_EMULATOR_HOST_VAR];
    }
    if (dbEmulatorHost) {
      isEmulator = true;
      dbUrl = `http://${dbEmulatorHost}?ns=${repoInfo.namespace}`;
      parsedUrl = parseRepoInfo(dbUrl, nodeAdmin);
      repoInfo = parsedUrl.repoInfo;
    } else {
      isEmulator = !parsedUrl.repoInfo.secure;
    }
    const authTokenProvider = nodeAdmin && isEmulator ? new EmulatorTokenProvider(EmulatorTokenProvider.OWNER) : new FirebaseAuthTokenProvider(app.name, app.options, authProvider);
    validateUrl("Invalid Firebase Database URL", parsedUrl);
    if (!pathIsEmpty(parsedUrl.path)) {
      fatal("Database URL must point to the root of a Firebase Database (not including a child path).");
    }
    const repo = repoManagerCreateRepo(repoInfo, app, authTokenProvider, new AppCheckTokenProvider(app.name, appCheckProvider));
    return new Database(repo, app);
  }
  function repoManagerDeleteRepo(repo, appName) {
    const appRepos = repos[appName];
    if (!appRepos || appRepos[repo.key] !== repo) {
      fatal(`Database ${appName}(${repo.repoInfo_}) has already been deleted.`);
    }
    repoInterrupt(repo);
    delete appRepos[repo.key];
  }
  function repoManagerCreateRepo(repoInfo, app, authTokenProvider, appCheckProvider) {
    let appRepos = repos[app.name];
    if (!appRepos) {
      appRepos = {};
      repos[app.name] = appRepos;
    }
    let repo = appRepos[repoInfo.toURLString()];
    if (repo) {
      fatal("Database initialized multiple times. Please make sure the format of the database URL matches with each database() call.");
    }
    repo = new Repo(repoInfo, useRestClient, authTokenProvider, appCheckProvider);
    appRepos[repoInfo.toURLString()] = repo;
    return repo;
  }
  class Database {
    /** @hideconstructor */
    constructor(_repoInternal, app) {
      this._repoInternal = _repoInternal;
      this.app = app;
      this["type"] = "database";
      this._instanceStarted = false;
    }
    get _repo() {
      if (!this._instanceStarted) {
        repoStart(this._repoInternal, this.app.options.appId, this.app.options["databaseAuthVariableOverride"]);
        this._instanceStarted = true;
      }
      return this._repoInternal;
    }
    get _root() {
      if (!this._rootInternal) {
        this._rootInternal = new ReferenceImpl(this._repo, newEmptyPath());
      }
      return this._rootInternal;
    }
    _delete() {
      if (this._rootInternal !== null) {
        repoManagerDeleteRepo(this._repo, this.app.name);
        this._repoInternal = null;
        this._rootInternal = null;
      }
      return Promise.resolve();
    }
    _checkNotDeleted(apiName) {
      if (this._rootInternal === null) {
        fatal("Cannot call " + apiName + " on a deleted database.");
      }
    }
  }
  function getDatabase(app = getApp(), url) {
    const db = _getProvider(app, "database").getImmediate({
      identifier: url
    });
    if (!db._instanceStarted) {
      const emulator = getDefaultEmulatorHostnameAndPort("database");
      if (emulator) {
        connectDatabaseEmulator(db, ...emulator);
      }
    }
    return db;
  }
  function connectDatabaseEmulator(db, host, port, options = {}) {
    db = getModularInstance(db);
    db._checkNotDeleted("useEmulator");
    if (db._instanceStarted) {
      fatal("Cannot call useEmulator() after instance has already been initialized.");
    }
    const repo = db._repoInternal;
    let tokenProvider = void 0;
    if (repo.repoInfo_.nodeAdmin) {
      if (options.mockUserToken) {
        fatal('mockUserToken is not supported by the Admin SDK. For client access with mock users, please use the "firebase" package instead of "firebase-admin".');
      }
      tokenProvider = new EmulatorTokenProvider(EmulatorTokenProvider.OWNER);
    } else if (options.mockUserToken) {
      const token = typeof options.mockUserToken === "string" ? options.mockUserToken : createMockUserToken(options.mockUserToken, db.app.options.projectId);
      tokenProvider = new EmulatorTokenProvider(token);
    }
    repoManagerApplyEmulatorSettings(repo, host, port, tokenProvider);
  }
  /**
   * @license
   * Copyright 2021 Google LLC
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
   *   http://www.apache.org/licenses/LICENSE-2.0
   *
   * Unless required by applicable law or agreed to in writing, software
   * distributed under the License is distributed on an "AS IS" BASIS,
   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   * See the License for the specific language governing permissions and
   * limitations under the License.
   */
  function registerDatabase(variant) {
    setSDKVersion(SDK_VERSION$1);
    _registerComponent(new Component(
      "database",
      (container, { instanceIdentifier: url }) => {
        const app = container.getProvider("app").getImmediate();
        const authProvider = container.getProvider("auth-internal");
        const appCheckProvider = container.getProvider("app-check-internal");
        return repoManagerDatabaseFromApp(app, authProvider, appCheckProvider, url);
      },
      "PUBLIC"
      /* ComponentType.PUBLIC */
    ).setMultipleInstances(true));
    registerVersion(name, version, variant);
    registerVersion(name, version, "esm2017");
  }
  PersistentConnection.prototype.simpleListen = function(pathString, onComplete) {
    this.sendRequest("q", { p: pathString }, onComplete);
  };
  PersistentConnection.prototype.echo = function(data, onEcho) {
    this.sendRequest("echo", { d: data }, onEcho);
  };
  registerDatabase();
  function getExerciseIdFromLocation() {
    const matchID = window.location.pathname.match(/\/exercise\/([0-9]+)/);
    return matchID ? matchID[1] : null;
  }
  function getPracticeSelectionURL({
    exerciseID,
    sectionsKeys
  }) {
    return `/practice/${exerciseID}/${sectionsKeys.join(",")}/start`;
  }
  function getExerciseURL({
    exerciseID
  }) {
    return `/exercise/${exerciseID}`;
  }
  function getPracticeSelectionURLFromSelectionContext({
    selectedExercise,
    selectedSections
  }) {
    return getPracticeSelectionURL({
      exerciseID: selectedExercise.exerciseID,
      sectionsKeys: getSectionKeysFromSelectionContext({
        selectedSections
      })
    });
  }
  function getExerciseURLFromSelectionContext({
    selectedExercise
  }) {
    return getExerciseURL({
      exerciseID: selectedExercise.exerciseID
    });
  }
  const CustomSelectionsToolbar = () => {
    const sectionSelectionContext = q$1(SectionSelectionContext);
    return o($3dc4ded751c8bdfb$export$be92b6f5f03c0fe9, {
      className: "ToolbarRoot CustomSelectionsToolbarRoot",
      "aria-label": "Formatting options",
      children: [o($3dc4ded751c8bdfb$export$353f5b6fc5456de1, {
        className: "ToolbarButton",
        disabled: sectionSelectionContext.selectedExercise.exerciseID !== getExerciseIdFromLocation() || sectionSelectionContext.selectedSections.length === 0,
        onClick: () => {
          sectionSelectionContext.setDialogueSaveSelectionsOpen();
        },
        children: [sectionSelectionContext.selectionStorageMatch && o(BookmarkFilledIcon, {}) || o(BookmarkIcon, {}), o("span", {
          className: "ToolbarButtonText",
          children: sectionSelectionContext.selectionStorageMatch && instance.t(`${LANG_NS_MAIN}:pageExercisePracticeToolbarSaveUpdateButton`) || instance.t(`${LANG_NS_MAIN}:pageExercisePracticeToolbarSaveButton`)
        })]
      }), o($3dc4ded751c8bdfb$export$353f5b6fc5456de1, {
        className: "ToolbarButton Warning",
        disabled: sectionSelectionContext.selectedExercise.exerciseID !== getExerciseIdFromLocation() || sectionSelectionContext.selectedSections.length === 0,
        style: {
          marginLeft: "auto"
        },
        onClick: sectionSelectionContext.reset,
        children: [o(CrossCircledIcon, {}), o("span", {
          className: "ToolbarButtonText",
          children: instance.t(`${LANG_NS_MAIN}:pageExercisePracticeToolbarResetButton`)
        })]
      }), sectionSelectionContext.selectedSections.length > 0 && sectionSelectionContext.selectedExercise.exerciseID === getExerciseIdFromLocation() && o($3dc4ded751c8bdfb$export$a6c7ac8248d6e38a, {
        className: "ToolbarLink",
        href: getPracticeSelectionURLFromSelectionContext(sectionSelectionContext),
        target: "_blank",
        style: {
          marginRight: 10
        },
        children: [o(ExternalLinkIcon, {}), instance.t(`${LANG_NS_MAIN}:pageExercisePracticeToolbarDirectLink`, {
          count: sectionSelectionContext.selectedSections.length,
          exercise: sectionSelectionContext.selectedExercise.exerciseTitle
        })]
      }) || o("span", {
        className: "ToolbarText",
        children: instance.t(`${LANG_NS_MAIN}:pageExercisePracticeToolbarDisabledLink`)
      })]
    });
  };
  function $addc16e1bbe58fd0$export$3a72a57244d6e765(onEscapeKeyDownProp, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) {
    const onEscapeKeyDown = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onEscapeKeyDownProp);
    p(() => {
      const handleKeyDown = (event) => {
        if (event.key === "Escape")
          onEscapeKeyDown(event);
      };
      ownerDocument.addEventListener("keydown", handleKeyDown);
      return () => ownerDocument.removeEventListener("keydown", handleKeyDown);
    }, [
      onEscapeKeyDown,
      ownerDocument
    ]);
  }
  const $5cb92bef7577960e$var$CONTEXT_UPDATE = "dismissableLayer.update";
  const $5cb92bef7577960e$var$POINTER_DOWN_OUTSIDE = "dismissableLayer.pointerDownOutside";
  const $5cb92bef7577960e$var$FOCUS_OUTSIDE = "dismissableLayer.focusOutside";
  let $5cb92bef7577960e$var$originalBodyPointerEvents;
  const $5cb92bef7577960e$var$DismissableLayerContext = /* @__PURE__ */ G$1({
    layers: /* @__PURE__ */ new Set(),
    layersWithOutsidePointerEventsDisabled: /* @__PURE__ */ new Set(),
    branches: /* @__PURE__ */ new Set()
  });
  const $5cb92bef7577960e$export$177fb62ff3ec1f22 = /* @__PURE__ */ k((props, forwardedRef) => {
    var _node$ownerDocument;
    const { disableOutsidePointerEvents = false, onEscapeKeyDown, onPointerDownOutside, onFocusOutside, onInteractOutside, onDismiss, ...layerProps } = props;
    const context = q$1($5cb92bef7577960e$var$DismissableLayerContext);
    const [node1, setNode] = h(null);
    const ownerDocument = (_node$ownerDocument = node1 === null || node1 === void 0 ? void 0 : node1.ownerDocument) !== null && _node$ownerDocument !== void 0 ? _node$ownerDocument : globalThis === null || globalThis === void 0 ? void 0 : globalThis.document;
    const [, force] = h({});
    const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(
      forwardedRef,
      (node) => setNode(node)
    );
    const layers = Array.from(context.layers);
    const [highestLayerWithOutsidePointerEventsDisabled] = [
      ...context.layersWithOutsidePointerEventsDisabled
    ].slice(-1);
    const highestLayerWithOutsidePointerEventsDisabledIndex = layers.indexOf(highestLayerWithOutsidePointerEventsDisabled);
    const index2 = node1 ? layers.indexOf(node1) : -1;
    const isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0;
    const isPointerEventsEnabled = index2 >= highestLayerWithOutsidePointerEventsDisabledIndex;
    const pointerDownOutside = $5cb92bef7577960e$var$usePointerDownOutside((event) => {
      const target = event.target;
      const isPointerDownOnBranch = [
        ...context.branches
      ].some(
        (branch) => branch.contains(target)
      );
      if (!isPointerEventsEnabled || isPointerDownOnBranch)
        return;
      onPointerDownOutside === null || onPointerDownOutside === void 0 || onPointerDownOutside(event);
      onInteractOutside === null || onInteractOutside === void 0 || onInteractOutside(event);
      if (!event.defaultPrevented)
        onDismiss === null || onDismiss === void 0 || onDismiss();
    }, ownerDocument);
    const focusOutside = $5cb92bef7577960e$var$useFocusOutside((event) => {
      const target = event.target;
      const isFocusInBranch = [
        ...context.branches
      ].some(
        (branch) => branch.contains(target)
      );
      if (isFocusInBranch)
        return;
      onFocusOutside === null || onFocusOutside === void 0 || onFocusOutside(event);
      onInteractOutside === null || onInteractOutside === void 0 || onInteractOutside(event);
      if (!event.defaultPrevented)
        onDismiss === null || onDismiss === void 0 || onDismiss();
    }, ownerDocument);
    $addc16e1bbe58fd0$export$3a72a57244d6e765((event) => {
      const isHighestLayer = index2 === context.layers.size - 1;
      if (!isHighestLayer)
        return;
      onEscapeKeyDown === null || onEscapeKeyDown === void 0 || onEscapeKeyDown(event);
      if (!event.defaultPrevented && onDismiss) {
        event.preventDefault();
        onDismiss();
      }
    }, ownerDocument);
    p(() => {
      if (!node1)
        return;
      if (disableOutsidePointerEvents) {
        if (context.layersWithOutsidePointerEventsDisabled.size === 0) {
          $5cb92bef7577960e$var$originalBodyPointerEvents = ownerDocument.body.style.pointerEvents;
          ownerDocument.body.style.pointerEvents = "none";
        }
        context.layersWithOutsidePointerEventsDisabled.add(node1);
      }
      context.layers.add(node1);
      $5cb92bef7577960e$var$dispatchUpdate();
      return () => {
        if (disableOutsidePointerEvents && context.layersWithOutsidePointerEventsDisabled.size === 1)
          ownerDocument.body.style.pointerEvents = $5cb92bef7577960e$var$originalBodyPointerEvents;
      };
    }, [
      node1,
      ownerDocument,
      disableOutsidePointerEvents,
      context
    ]);
    p(() => {
      return () => {
        if (!node1)
          return;
        context.layers.delete(node1);
        context.layersWithOutsidePointerEventsDisabled.delete(node1);
        $5cb92bef7577960e$var$dispatchUpdate();
      };
    }, [
      node1,
      context
    ]);
    p(() => {
      const handleUpdate = () => force({});
      document.addEventListener($5cb92bef7577960e$var$CONTEXT_UPDATE, handleUpdate);
      return () => document.removeEventListener($5cb92bef7577960e$var$CONTEXT_UPDATE, handleUpdate);
    }, []);
    return /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends({}, layerProps, {
      ref: composedRefs,
      style: {
        pointerEvents: isBodyPointerEventsDisabled ? isPointerEventsEnabled ? "auto" : "none" : void 0,
        ...props.style
      },
      onFocusCapture: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onFocusCapture, focusOutside.onFocusCapture),
      onBlurCapture: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onBlurCapture, focusOutside.onBlurCapture),
      onPointerDownCapture: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerDownCapture, pointerDownOutside.onPointerDownCapture)
    }));
  });
  const $5cb92bef7577960e$export$4d5eb2109db14228 = /* @__PURE__ */ k((props, forwardedRef) => {
    const context = q$1($5cb92bef7577960e$var$DismissableLayerContext);
    const ref2 = _$2(null);
    const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref2);
    p(() => {
      const node = ref2.current;
      if (node) {
        context.branches.add(node);
        return () => {
          context.branches.delete(node);
        };
      }
    }, [
      context.branches
    ]);
    return /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends({}, props, {
      ref: composedRefs
    }));
  });
  function $5cb92bef7577960e$var$usePointerDownOutside(onPointerDownOutside, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) {
    const handlePointerDownOutside = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onPointerDownOutside);
    const isPointerInsideReactTreeRef = _$2(false);
    const handleClickRef = _$2(() => {
    });
    p(() => {
      const handlePointerDown = (event) => {
        if (event.target && !isPointerInsideReactTreeRef.current) {
          let handleAndDispatchPointerDownOutsideEvent2 = function() {
            $5cb92bef7577960e$var$handleAndDispatchCustomEvent($5cb92bef7577960e$var$POINTER_DOWN_OUTSIDE, handlePointerDownOutside, eventDetail, {
              discrete: true
            });
          };
          const eventDetail = {
            originalEvent: event
          };
          if (event.pointerType === "touch") {
            ownerDocument.removeEventListener("click", handleClickRef.current);
            handleClickRef.current = handleAndDispatchPointerDownOutsideEvent2;
            ownerDocument.addEventListener("click", handleClickRef.current, {
              once: true
            });
          } else
            handleAndDispatchPointerDownOutsideEvent2();
        }
        isPointerInsideReactTreeRef.current = false;
      };
      const timerId = window.setTimeout(() => {
        ownerDocument.addEventListener("pointerdown", handlePointerDown);
      }, 0);
      return () => {
        window.clearTimeout(timerId);
        ownerDocument.removeEventListener("pointerdown", handlePointerDown);
        ownerDocument.removeEventListener("click", handleClickRef.current);
      };
    }, [
      ownerDocument,
      handlePointerDownOutside
    ]);
    return {
      // ensures we check React component tree (not just DOM tree)
      onPointerDownCapture: () => isPointerInsideReactTreeRef.current = true
    };
  }
  function $5cb92bef7577960e$var$useFocusOutside(onFocusOutside, ownerDocument = globalThis === null || globalThis === void 0 ? void 0 : globalThis.document) {
    const handleFocusOutside = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onFocusOutside);
    const isFocusInsideReactTreeRef = _$2(false);
    p(() => {
      const handleFocus = (event) => {
        if (event.target && !isFocusInsideReactTreeRef.current) {
          const eventDetail = {
            originalEvent: event
          };
          $5cb92bef7577960e$var$handleAndDispatchCustomEvent($5cb92bef7577960e$var$FOCUS_OUTSIDE, handleFocusOutside, eventDetail, {
            discrete: false
          });
        }
      };
      ownerDocument.addEventListener("focusin", handleFocus);
      return () => ownerDocument.removeEventListener("focusin", handleFocus);
    }, [
      ownerDocument,
      handleFocusOutside
    ]);
    return {
      onFocusCapture: () => isFocusInsideReactTreeRef.current = true,
      onBlurCapture: () => isFocusInsideReactTreeRef.current = false
    };
  }
  function $5cb92bef7577960e$var$dispatchUpdate() {
    const event = new CustomEvent($5cb92bef7577960e$var$CONTEXT_UPDATE);
    document.dispatchEvent(event);
  }
  function $5cb92bef7577960e$var$handleAndDispatchCustomEvent(name2, handler, detail, { discrete }) {
    const target = detail.originalEvent.target;
    const event = new CustomEvent(name2, {
      bubbles: false,
      cancelable: true,
      detail
    });
    if (handler)
      target.addEventListener(name2, handler, {
        once: true
      });
    if (discrete)
      $8927f6f2acc4f386$export$6d1a0317bde7de7f(target, event);
    else
      target.dispatchEvent(event);
  }
  const $5cb92bef7577960e$export$be92b6f5f03c0fe9 = $5cb92bef7577960e$export$177fb62ff3ec1f22;
  const $5cb92bef7577960e$export$aecb2ddcb55c95be = $5cb92bef7577960e$export$4d5eb2109db14228;
  const $d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT = "focusScope.autoFocusOnMount";
  const $d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT = "focusScope.autoFocusOnUnmount";
  const $d3863c46a17e8a28$var$EVENT_OPTIONS = {
    bubbles: false,
    cancelable: true
  };
  const $d3863c46a17e8a28$export$20e40289641fbbb6 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { loop = false, trapped = false, onMountAutoFocus: onMountAutoFocusProp, onUnmountAutoFocus: onUnmountAutoFocusProp, ...scopeProps } = props;
    const [container1, setContainer] = h(null);
    const onMountAutoFocus = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onMountAutoFocusProp);
    const onUnmountAutoFocus = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(onUnmountAutoFocusProp);
    const lastFocusedElementRef = _$2(null);
    const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(
      forwardedRef,
      (node) => setContainer(node)
    );
    const focusScope = _$2({
      paused: false,
      pause() {
        this.paused = true;
      },
      resume() {
        this.paused = false;
      }
    }).current;
    p(() => {
      if (trapped) {
        let handleFocusIn2 = function(event) {
          if (focusScope.paused || !container1)
            return;
          const target = event.target;
          if (container1.contains(target))
            lastFocusedElementRef.current = target;
          else
            $d3863c46a17e8a28$var$focus(lastFocusedElementRef.current, {
              select: true
            });
        }, handleFocusOut2 = function(event) {
          if (focusScope.paused || !container1)
            return;
          const relatedTarget = event.relatedTarget;
          if (relatedTarget === null)
            return;
          if (!container1.contains(relatedTarget))
            $d3863c46a17e8a28$var$focus(lastFocusedElementRef.current, {
              select: true
            });
        }, handleMutations2 = function(mutations) {
          const focusedElement = document.activeElement;
          for (const mutation of mutations) {
            if (mutation.removedNodes.length > 0) {
              if (!(container1 !== null && container1 !== void 0 && container1.contains(focusedElement)))
                $d3863c46a17e8a28$var$focus(container1);
            }
          }
        };
        document.addEventListener("focusin", handleFocusIn2);
        document.addEventListener("focusout", handleFocusOut2);
        const mutationObserver = new MutationObserver(handleMutations2);
        if (container1)
          mutationObserver.observe(container1, {
            childList: true,
            subtree: true
          });
        return () => {
          document.removeEventListener("focusin", handleFocusIn2);
          document.removeEventListener("focusout", handleFocusOut2);
          mutationObserver.disconnect();
        };
      }
    }, [
      trapped,
      container1,
      focusScope.paused
    ]);
    p(() => {
      if (container1) {
        $d3863c46a17e8a28$var$focusScopesStack.add(focusScope);
        const previouslyFocusedElement = document.activeElement;
        const hasFocusedCandidate = container1.contains(previouslyFocusedElement);
        if (!hasFocusedCandidate) {
          const mountEvent = new CustomEvent($d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT, $d3863c46a17e8a28$var$EVENT_OPTIONS);
          container1.addEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT, onMountAutoFocus);
          container1.dispatchEvent(mountEvent);
          if (!mountEvent.defaultPrevented) {
            $d3863c46a17e8a28$var$focusFirst($d3863c46a17e8a28$var$removeLinks($d3863c46a17e8a28$var$getTabbableCandidates(container1)), {
              select: true
            });
            if (document.activeElement === previouslyFocusedElement)
              $d3863c46a17e8a28$var$focus(container1);
          }
        }
        return () => {
          container1.removeEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_MOUNT, onMountAutoFocus);
          setTimeout(() => {
            const unmountEvent = new CustomEvent($d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT, $d3863c46a17e8a28$var$EVENT_OPTIONS);
            container1.addEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
            container1.dispatchEvent(unmountEvent);
            if (!unmountEvent.defaultPrevented)
              $d3863c46a17e8a28$var$focus(previouslyFocusedElement !== null && previouslyFocusedElement !== void 0 ? previouslyFocusedElement : document.body, {
                select: true
              });
            container1.removeEventListener($d3863c46a17e8a28$var$AUTOFOCUS_ON_UNMOUNT, onUnmountAutoFocus);
            $d3863c46a17e8a28$var$focusScopesStack.remove(focusScope);
          }, 0);
        };
      }
    }, [
      container1,
      onMountAutoFocus,
      onUnmountAutoFocus,
      focusScope
    ]);
    const handleKeyDown = T$1((event) => {
      if (!loop && !trapped)
        return;
      if (focusScope.paused)
        return;
      const isTabKey = event.key === "Tab" && !event.altKey && !event.ctrlKey && !event.metaKey;
      const focusedElement = document.activeElement;
      if (isTabKey && focusedElement) {
        const container = event.currentTarget;
        const [first, last] = $d3863c46a17e8a28$var$getTabbableEdges(container);
        const hasTabbableElementsInside = first && last;
        if (!hasTabbableElementsInside) {
          if (focusedElement === container)
            event.preventDefault();
        } else {
          if (!event.shiftKey && focusedElement === last) {
            event.preventDefault();
            if (loop)
              $d3863c46a17e8a28$var$focus(first, {
                select: true
              });
          } else if (event.shiftKey && focusedElement === first) {
            event.preventDefault();
            if (loop)
              $d3863c46a17e8a28$var$focus(last, {
                select: true
              });
          }
        }
      }
    }, [
      loop,
      trapped,
      focusScope.paused
    ]);
    return /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends({
      tabIndex: -1
    }, scopeProps, {
      ref: composedRefs,
      onKeyDown: handleKeyDown
    }));
  });
  function $d3863c46a17e8a28$var$focusFirst(candidates, { select = false } = {}) {
    const previouslyFocusedElement = document.activeElement;
    for (const candidate of candidates) {
      $d3863c46a17e8a28$var$focus(candidate, {
        select
      });
      if (document.activeElement !== previouslyFocusedElement)
        return;
    }
  }
  function $d3863c46a17e8a28$var$getTabbableEdges(container) {
    const candidates = $d3863c46a17e8a28$var$getTabbableCandidates(container);
    const first = $d3863c46a17e8a28$var$findVisible(candidates, container);
    const last = $d3863c46a17e8a28$var$findVisible(candidates.reverse(), container);
    return [
      first,
      last
    ];
  }
  function $d3863c46a17e8a28$var$getTabbableCandidates(container) {
    const nodes = [];
    const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
      acceptNode: (node) => {
        const isHiddenInput = node.tagName === "INPUT" && node.type === "hidden";
        if (node.disabled || node.hidden || isHiddenInput)
          return NodeFilter.FILTER_SKIP;
        return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
      }
    });
    while (walker.nextNode())
      nodes.push(walker.currentNode);
    return nodes;
  }
  function $d3863c46a17e8a28$var$findVisible(elements, container) {
    for (const element of elements) {
      if (!$d3863c46a17e8a28$var$isHidden(element, {
        upTo: container
      }))
        return element;
    }
  }
  function $d3863c46a17e8a28$var$isHidden(node, { upTo }) {
    if (getComputedStyle(node).visibility === "hidden")
      return true;
    while (node) {
      if (upTo !== void 0 && node === upTo)
        return false;
      if (getComputedStyle(node).display === "none")
        return true;
      node = node.parentElement;
    }
    return false;
  }
  function $d3863c46a17e8a28$var$isSelectableInput(element) {
    return element instanceof HTMLInputElement && "select" in element;
  }
  function $d3863c46a17e8a28$var$focus(element, { select = false } = {}) {
    if (element && element.focus) {
      const previouslyFocusedElement = document.activeElement;
      element.focus({
        preventScroll: true
      });
      if (element !== previouslyFocusedElement && $d3863c46a17e8a28$var$isSelectableInput(element) && select)
        element.select();
    }
  }
  const $d3863c46a17e8a28$var$focusScopesStack = $d3863c46a17e8a28$var$createFocusScopesStack();
  function $d3863c46a17e8a28$var$createFocusScopesStack() {
    let stack = [];
    return {
      add(focusScope) {
        const activeFocusScope = stack[0];
        if (focusScope !== activeFocusScope)
          activeFocusScope === null || activeFocusScope === void 0 || activeFocusScope.pause();
        stack = $d3863c46a17e8a28$var$arrayRemove(stack, focusScope);
        stack.unshift(focusScope);
      },
      remove(focusScope) {
        var _stack$;
        stack = $d3863c46a17e8a28$var$arrayRemove(stack, focusScope);
        (_stack$ = stack[0]) === null || _stack$ === void 0 || _stack$.resume();
      }
    };
  }
  function $d3863c46a17e8a28$var$arrayRemove(array, item) {
    const updatedArray = [
      ...array
    ];
    const index2 = updatedArray.indexOf(item);
    if (index2 !== -1)
      updatedArray.splice(index2, 1);
    return updatedArray;
  }
  function $d3863c46a17e8a28$var$removeLinks(items) {
    return items.filter(
      (item) => item.tagName !== "A"
    );
  }
  const $f1701beae083dbae$export$602eac185826482c = /* @__PURE__ */ k((props, forwardedRef) => {
    var _globalThis$document;
    const { container = globalThis === null || globalThis === void 0 ? void 0 : (_globalThis$document = globalThis.document) === null || _globalThis$document === void 0 ? void 0 : _globalThis$document.body, ...portalProps } = props;
    return container ? /* @__PURE__ */ Cn.createPortal(/* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends({}, portalProps, {
      ref: forwardedRef
    })), container) : null;
  });
  let $3db38b7d1fb3fe6a$var$count = 0;
  function $3db38b7d1fb3fe6a$export$b7ece24a22aeda8c() {
    p(() => {
      var _edgeGuards$, _edgeGuards$2;
      const edgeGuards = document.querySelectorAll("[data-radix-focus-guard]");
      document.body.insertAdjacentElement("afterbegin", (_edgeGuards$ = edgeGuards[0]) !== null && _edgeGuards$ !== void 0 ? _edgeGuards$ : $3db38b7d1fb3fe6a$var$createFocusGuard());
      document.body.insertAdjacentElement("beforeend", (_edgeGuards$2 = edgeGuards[1]) !== null && _edgeGuards$2 !== void 0 ? _edgeGuards$2 : $3db38b7d1fb3fe6a$var$createFocusGuard());
      $3db38b7d1fb3fe6a$var$count++;
      return () => {
        if ($3db38b7d1fb3fe6a$var$count === 1)
          document.querySelectorAll("[data-radix-focus-guard]").forEach(
            (node) => node.remove()
          );
        $3db38b7d1fb3fe6a$var$count--;
      };
    }, []);
  }
  function $3db38b7d1fb3fe6a$var$createFocusGuard() {
    const element = document.createElement("span");
    element.setAttribute("data-radix-focus-guard", "");
    element.tabIndex = 0;
    element.style.cssText = "outline: none; opacity: 0; position: fixed; pointer-events: none";
    return element;
  }
  var __assign = function() {
    __assign = Object.assign || function __assign2(t2) {
      for (var s2, i2 = 1, n2 = arguments.length; i2 < n2; i2++) {
        s2 = arguments[i2];
        for (var p2 in s2)
          if (Object.prototype.hasOwnProperty.call(s2, p2))
            t2[p2] = s2[p2];
      }
      return t2;
    };
    return __assign.apply(this, arguments);
  };
  function __rest(s2, e2) {
    var t2 = {};
    for (var p2 in s2)
      if (Object.prototype.hasOwnProperty.call(s2, p2) && e2.indexOf(p2) < 0)
        t2[p2] = s2[p2];
    if (s2 != null && typeof Object.getOwnPropertySymbols === "function")
      for (var i2 = 0, p2 = Object.getOwnPropertySymbols(s2); i2 < p2.length; i2++) {
        if (e2.indexOf(p2[i2]) < 0 && Object.prototype.propertyIsEnumerable.call(s2, p2[i2]))
          t2[p2[i2]] = s2[p2[i2]];
      }
    return t2;
  }
  function __spreadArray(to, from, pack) {
    if (pack || arguments.length === 2)
      for (var i2 = 0, l2 = from.length, ar; i2 < l2; i2++) {
        if (ar || !(i2 in from)) {
          if (!ar)
            ar = Array.prototype.slice.call(from, 0, i2);
          ar[i2] = from[i2];
        }
      }
    return to.concat(ar || Array.prototype.slice.call(from));
  }
  typeof SuppressedError === "function" ? SuppressedError : function(error2, suppressed, message) {
    var e2 = new Error(message);
    return e2.name = "SuppressedError", e2.error = error2, e2.suppressed = suppressed, e2;
  };
  var zeroRightClassName = "right-scroll-bar-position";
  var fullWidthClassName = "width-before-scroll-bar";
  var noScrollbarsClassName = "with-scroll-bars-hidden";
  var removedBarSizeVariable = "--removed-body-scroll-bar-size";
  function assignRef(ref2, value) {
    if (typeof ref2 === "function") {
      ref2(value);
    } else if (ref2) {
      ref2.current = value;
    }
    return ref2;
  }
  function useCallbackRef(initialValue, callback) {
    var ref2 = h(function() {
      return {
        // value
        value: initialValue,
        // last callback
        callback,
        // "memoized" public interface
        facade: {
          get current() {
            return ref2.value;
          },
          set current(value) {
            var last = ref2.value;
            if (last !== value) {
              ref2.value = value;
              ref2.callback(value, last);
            }
          }
        }
      };
    })[0];
    ref2.callback = callback;
    return ref2.facade;
  }
  function useMergeRefs(refs, defaultValue2) {
    return useCallbackRef(defaultValue2 || null, function(newValue) {
      return refs.forEach(function(ref2) {
        return assignRef(ref2, newValue);
      });
    });
  }
  function ItoI(a2) {
    return a2;
  }
  function innerCreateMedium(defaults, middleware) {
    if (middleware === void 0) {
      middleware = ItoI;
    }
    var buffer = [];
    var assigned = false;
    var medium = {
      read: function() {
        if (assigned) {
          throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");
        }
        if (buffer.length) {
          return buffer[buffer.length - 1];
        }
        return defaults;
      },
      useMedium: function(data) {
        var item = middleware(data, assigned);
        buffer.push(item);
        return function() {
          buffer = buffer.filter(function(x2) {
            return x2 !== item;
          });
        };
      },
      assignSyncMedium: function(cb) {
        assigned = true;
        while (buffer.length) {
          var cbs = buffer;
          buffer = [];
          cbs.forEach(cb);
        }
        buffer = {
          push: function(x2) {
            return cb(x2);
          },
          filter: function() {
            return buffer;
          }
        };
      },
      assignMedium: function(cb) {
        assigned = true;
        var pendingQueue = [];
        if (buffer.length) {
          var cbs = buffer;
          buffer = [];
          cbs.forEach(cb);
          pendingQueue = buffer;
        }
        var executeQueue = function() {
          var cbs2 = pendingQueue;
          pendingQueue = [];
          cbs2.forEach(cb);
        };
        var cycle = function() {
          return Promise.resolve().then(executeQueue);
        };
        cycle();
        buffer = {
          push: function(x2) {
            pendingQueue.push(x2);
            cycle();
          },
          filter: function(filter) {
            pendingQueue = pendingQueue.filter(filter);
            return buffer;
          }
        };
      }
    };
    return medium;
  }
  function createSidecarMedium(options) {
    if (options === void 0) {
      options = {};
    }
    var medium = innerCreateMedium(null);
    medium.options = __assign({ async: true, ssr: false }, options);
    return medium;
  }
  var SideCar$1 = function(_a2) {
    var sideCar = _a2.sideCar, rest = __rest(_a2, ["sideCar"]);
    if (!sideCar) {
      throw new Error("Sidecar: please provide `sideCar` property to import the right car");
    }
    var Target = sideCar.read();
    if (!Target) {
      throw new Error("Sidecar medium not found");
    }
    return y$1(Target, __assign({}, rest));
  };
  SideCar$1.isSideCarExport = true;
  function exportSidecar(medium, exported) {
    medium.useMedium(exported);
    return SideCar$1;
  }
  var effectCar = createSidecarMedium();
  var nothing = function() {
    return;
  };
  var RemoveScroll = k(function(props, parentRef) {
    var ref2 = _$2(null);
    var _a2 = h({
      onScrollCapture: nothing,
      onWheelCapture: nothing,
      onTouchMoveCapture: nothing
    }), callbacks = _a2[0], setCallbacks = _a2[1];
    var forwardProps = props.forwardProps, children = props.children, className = props.className, removeScrollBar = props.removeScrollBar, enabled = props.enabled, shards = props.shards, sideCar = props.sideCar, noIsolation = props.noIsolation, inert = props.inert, allowPinchZoom = props.allowPinchZoom, _b = props.as, Container = _b === void 0 ? "div" : _b, rest = __rest(props, ["forwardProps", "children", "className", "removeScrollBar", "enabled", "shards", "sideCar", "noIsolation", "inert", "allowPinchZoom", "as"]);
    var SideCar2 = sideCar;
    var containerRef = useMergeRefs([ref2, parentRef]);
    var containerProps = __assign(__assign({}, rest), callbacks);
    return y$1(
      k$2,
      null,
      enabled && y$1(SideCar2, { sideCar: effectCar, removeScrollBar, shards, noIsolation, inert, setCallbacks, allowPinchZoom: !!allowPinchZoom, lockRef: ref2 }),
      forwardProps ? sn(O.only(children), __assign(__assign({}, containerProps), { ref: containerRef })) : y$1(Container, __assign({}, containerProps, { className, ref: containerRef }), children)
    );
  });
  RemoveScroll.defaultProps = {
    enabled: true,
    removeScrollBar: true,
    inert: false
  };
  RemoveScroll.classNames = {
    fullWidth: fullWidthClassName,
    zeroRight: zeroRightClassName
  };
  var getNonce = function() {
    if (typeof __webpack_nonce__ !== "undefined") {
      return __webpack_nonce__;
    }
    return void 0;
  };
  function makeStyleTag() {
    if (!document)
      return null;
    var tag = document.createElement("style");
    tag.type = "text/css";
    var nonce = getNonce();
    if (nonce) {
      tag.setAttribute("nonce", nonce);
    }
    return tag;
  }
  function injectStyles(tag, css) {
    if (tag.styleSheet) {
      tag.styleSheet.cssText = css;
    } else {
      tag.appendChild(document.createTextNode(css));
    }
  }
  function insertStyleTag(tag) {
    var head = document.head || document.getElementsByTagName("head")[0];
    head.appendChild(tag);
  }
  var stylesheetSingleton = function() {
    var counter = 0;
    var stylesheet = null;
    return {
      add: function(style) {
        if (counter == 0) {
          if (stylesheet = makeStyleTag()) {
            injectStyles(stylesheet, style);
            insertStyleTag(stylesheet);
          }
        }
        counter++;
      },
      remove: function() {
        counter--;
        if (!counter && stylesheet) {
          stylesheet.parentNode && stylesheet.parentNode.removeChild(stylesheet);
          stylesheet = null;
        }
      }
    };
  };
  var styleHookSingleton = function() {
    var sheet = stylesheetSingleton();
    return function(styles2, isDynamic) {
      p(function() {
        sheet.add(styles2);
        return function() {
          sheet.remove();
        };
      }, [styles2 && isDynamic]);
    };
  };
  var styleSingleton = function() {
    var useStyle = styleHookSingleton();
    var Sheet = function(_a2) {
      var styles2 = _a2.styles, dynamic = _a2.dynamic;
      useStyle(styles2, dynamic);
      return null;
    };
    return Sheet;
  };
  var zeroGap = {
    left: 0,
    top: 0,
    right: 0,
    gap: 0
  };
  var parse = function(x2) {
    return parseInt(x2 || "", 10) || 0;
  };
  var getOffset = function(gapMode) {
    var cs = window.getComputedStyle(document.body);
    var left = cs[gapMode === "padding" ? "paddingLeft" : "marginLeft"];
    var top = cs[gapMode === "padding" ? "paddingTop" : "marginTop"];
    var right = cs[gapMode === "padding" ? "paddingRight" : "marginRight"];
    return [parse(left), parse(top), parse(right)];
  };
  var getGapWidth = function(gapMode) {
    if (gapMode === void 0) {
      gapMode = "margin";
    }
    if (typeof window === "undefined") {
      return zeroGap;
    }
    var offsets = getOffset(gapMode);
    var documentWidth = document.documentElement.clientWidth;
    var windowWidth = window.innerWidth;
    return {
      left: offsets[0],
      top: offsets[1],
      right: offsets[2],
      gap: Math.max(0, windowWidth - documentWidth + offsets[2] - offsets[0])
    };
  };
  var Style = styleSingleton();
  var getStyles = function(_a2, allowRelative, gapMode, important) {
    var left = _a2.left, top = _a2.top, right = _a2.right, gap = _a2.gap;
    if (gapMode === void 0) {
      gapMode = "margin";
    }
    return "\n  .".concat(noScrollbarsClassName, " {\n   overflow: hidden ").concat(important, ";\n   padding-right: ").concat(gap, "px ").concat(important, ";\n  }\n  body {\n    overflow: hidden ").concat(important, ";\n    overscroll-behavior: contain;\n    ").concat([
      allowRelative && "position: relative ".concat(important, ";"),
      gapMode === "margin" && "\n    padding-left: ".concat(left, "px;\n    padding-top: ").concat(top, "px;\n    padding-right: ").concat(right, "px;\n    margin-left:0;\n    margin-top:0;\n    margin-right: ").concat(gap, "px ").concat(important, ";\n    "),
      gapMode === "padding" && "padding-right: ".concat(gap, "px ").concat(important, ";")
    ].filter(Boolean).join(""), "\n  }\n  \n  .").concat(zeroRightClassName, " {\n    right: ").concat(gap, "px ").concat(important, ";\n  }\n  \n  .").concat(fullWidthClassName, " {\n    margin-right: ").concat(gap, "px ").concat(important, ";\n  }\n  \n  .").concat(zeroRightClassName, " .").concat(zeroRightClassName, " {\n    right: 0 ").concat(important, ";\n  }\n  \n  .").concat(fullWidthClassName, " .").concat(fullWidthClassName, " {\n    margin-right: 0 ").concat(important, ";\n  }\n  \n  body {\n    ").concat(removedBarSizeVariable, ": ").concat(gap, "px;\n  }\n");
  };
  var RemoveScrollBar = function(props) {
    var noRelative = props.noRelative, noImportant = props.noImportant, _a2 = props.gapMode, gapMode = _a2 === void 0 ? "margin" : _a2;
    var gap = F$1(function() {
      return getGapWidth(gapMode);
    }, [gapMode]);
    return y$1(Style, { styles: getStyles(gap, !noRelative, gapMode, !noImportant ? "!important" : "") });
  };
  var passiveSupported = false;
  if (typeof window !== "undefined") {
    try {
      var options = Object.defineProperty({}, "passive", {
        get: function() {
          passiveSupported = true;
          return true;
        }
      });
      window.addEventListener("test", options, options);
      window.removeEventListener("test", options, options);
    } catch (err) {
      passiveSupported = false;
    }
  }
  var nonPassive = passiveSupported ? { passive: false } : false;
  var alwaysContainsScroll = function(node) {
    return node.tagName === "TEXTAREA";
  };
  var elementCanBeScrolled = function(node, overflow) {
    var styles2 = window.getComputedStyle(node);
    return (
      // not-not-scrollable
      styles2[overflow] !== "hidden" && // contains scroll inside self
      !(styles2.overflowY === styles2.overflowX && !alwaysContainsScroll(node) && styles2[overflow] === "visible")
    );
  };
  var elementCouldBeVScrolled = function(node) {
    return elementCanBeScrolled(node, "overflowY");
  };
  var elementCouldBeHScrolled = function(node) {
    return elementCanBeScrolled(node, "overflowX");
  };
  var locationCouldBeScrolled = function(axis, node) {
    var current = node;
    do {
      if (typeof ShadowRoot !== "undefined" && current instanceof ShadowRoot) {
        current = current.host;
      }
      var isScrollable2 = elementCouldBeScrolled(axis, current);
      if (isScrollable2) {
        var _a2 = getScrollVariables(axis, current), s2 = _a2[1], d2 = _a2[2];
        if (s2 > d2) {
          return true;
        }
      }
      current = current.parentNode;
    } while (current && current !== document.body);
    return false;
  };
  var getVScrollVariables = function(_a2) {
    var scrollTop = _a2.scrollTop, scrollHeight = _a2.scrollHeight, clientHeight = _a2.clientHeight;
    return [
      scrollTop,
      scrollHeight,
      clientHeight
    ];
  };
  var getHScrollVariables = function(_a2) {
    var scrollLeft = _a2.scrollLeft, scrollWidth = _a2.scrollWidth, clientWidth = _a2.clientWidth;
    return [
      scrollLeft,
      scrollWidth,
      clientWidth
    ];
  };
  var elementCouldBeScrolled = function(axis, node) {
    return axis === "v" ? elementCouldBeVScrolled(node) : elementCouldBeHScrolled(node);
  };
  var getScrollVariables = function(axis, node) {
    return axis === "v" ? getVScrollVariables(node) : getHScrollVariables(node);
  };
  var getDirectionFactor = function(axis, direction) {
    return axis === "h" && direction === "rtl" ? -1 : 1;
  };
  var handleScroll = function(axis, endTarget, event, sourceDelta, noOverscroll) {
    var directionFactor = getDirectionFactor(axis, window.getComputedStyle(endTarget).direction);
    var delta = directionFactor * sourceDelta;
    var target = event.target;
    var targetInLock = endTarget.contains(target);
    var shouldCancelScroll = false;
    var isDeltaPositive = delta > 0;
    var availableScroll = 0;
    var availableScrollTop = 0;
    do {
      var _a2 = getScrollVariables(axis, target), position = _a2[0], scroll_1 = _a2[1], capacity = _a2[2];
      var elementScroll = scroll_1 - capacity - directionFactor * position;
      if (position || elementScroll) {
        if (elementCouldBeScrolled(axis, target)) {
          availableScroll += elementScroll;
          availableScrollTop += position;
        }
      }
      target = target.parentNode;
    } while (
      // portaled content
      !targetInLock && target !== document.body || // self content
      targetInLock && (endTarget.contains(target) || endTarget === target)
    );
    if (isDeltaPositive && (noOverscroll && availableScroll === 0 || !noOverscroll && delta > availableScroll)) {
      shouldCancelScroll = true;
    } else if (!isDeltaPositive && (noOverscroll && availableScrollTop === 0 || !noOverscroll && -delta > availableScrollTop)) {
      shouldCancelScroll = true;
    }
    return shouldCancelScroll;
  };
  var getTouchXY = function(event) {
    return "changedTouches" in event ? [event.changedTouches[0].clientX, event.changedTouches[0].clientY] : [0, 0];
  };
  var getDeltaXY = function(event) {
    return [event.deltaX, event.deltaY];
  };
  var extractRef = function(ref2) {
    return ref2 && "current" in ref2 ? ref2.current : ref2;
  };
  var deltaCompare = function(x2, y2) {
    return x2[0] === y2[0] && x2[1] === y2[1];
  };
  var generateStyle = function(id) {
    return "\n  .block-interactivity-".concat(id, " {pointer-events: none;}\n  .allow-interactivity-").concat(id, " {pointer-events: all;}\n");
  };
  var idCounter = 0;
  var lockStack = [];
  function RemoveScrollSideCar(props) {
    var shouldPreventQueue = _$2([]);
    var touchStartRef = _$2([0, 0]);
    var activeAxis = _$2();
    var id = h(idCounter++)[0];
    var Style2 = h(function() {
      return styleSingleton();
    })[0];
    var lastProps = _$2(props);
    p(function() {
      lastProps.current = props;
    }, [props]);
    p(function() {
      if (props.inert) {
        document.body.classList.add("block-interactivity-".concat(id));
        var allow_1 = __spreadArray([props.lockRef.current], (props.shards || []).map(extractRef), true).filter(Boolean);
        allow_1.forEach(function(el) {
          return el.classList.add("allow-interactivity-".concat(id));
        });
        return function() {
          document.body.classList.remove("block-interactivity-".concat(id));
          allow_1.forEach(function(el) {
            return el.classList.remove("allow-interactivity-".concat(id));
          });
        };
      }
      return;
    }, [props.inert, props.lockRef.current, props.shards]);
    var shouldCancelEvent = T$1(function(event, parent) {
      if ("touches" in event && event.touches.length === 2) {
        return !lastProps.current.allowPinchZoom;
      }
      var touch = getTouchXY(event);
      var touchStart = touchStartRef.current;
      var deltaX = "deltaX" in event ? event.deltaX : touchStart[0] - touch[0];
      var deltaY = "deltaY" in event ? event.deltaY : touchStart[1] - touch[1];
      var currentAxis;
      var target = event.target;
      var moveDirection = Math.abs(deltaX) > Math.abs(deltaY) ? "h" : "v";
      if ("touches" in event && moveDirection === "h" && target.type === "range") {
        return false;
      }
      var canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target);
      if (!canBeScrolledInMainDirection) {
        return true;
      }
      if (canBeScrolledInMainDirection) {
        currentAxis = moveDirection;
      } else {
        currentAxis = moveDirection === "v" ? "h" : "v";
        canBeScrolledInMainDirection = locationCouldBeScrolled(moveDirection, target);
      }
      if (!canBeScrolledInMainDirection) {
        return false;
      }
      if (!activeAxis.current && "changedTouches" in event && (deltaX || deltaY)) {
        activeAxis.current = currentAxis;
      }
      if (!currentAxis) {
        return true;
      }
      var cancelingAxis = activeAxis.current || currentAxis;
      return handleScroll(cancelingAxis, parent, event, cancelingAxis === "h" ? deltaX : deltaY, true);
    }, []);
    var shouldPrevent = T$1(function(_event) {
      var event = _event;
      if (!lockStack.length || lockStack[lockStack.length - 1] !== Style2) {
        return;
      }
      var delta = "deltaY" in event ? getDeltaXY(event) : getTouchXY(event);
      var sourceEvent = shouldPreventQueue.current.filter(function(e2) {
        return e2.name === event.type && e2.target === event.target && deltaCompare(e2.delta, delta);
      })[0];
      if (sourceEvent && sourceEvent.should) {
        if (event.cancelable) {
          event.preventDefault();
        }
        return;
      }
      if (!sourceEvent) {
        var shardNodes = (lastProps.current.shards || []).map(extractRef).filter(Boolean).filter(function(node) {
          return node.contains(event.target);
        });
        var shouldStop = shardNodes.length > 0 ? shouldCancelEvent(event, shardNodes[0]) : !lastProps.current.noIsolation;
        if (shouldStop) {
          if (event.cancelable) {
            event.preventDefault();
          }
        }
      }
    }, []);
    var shouldCancel = T$1(function(name2, delta, target, should) {
      var event = { name: name2, delta, target, should };
      shouldPreventQueue.current.push(event);
      setTimeout(function() {
        shouldPreventQueue.current = shouldPreventQueue.current.filter(function(e2) {
          return e2 !== event;
        });
      }, 1);
    }, []);
    var scrollTouchStart = T$1(function(event) {
      touchStartRef.current = getTouchXY(event);
      activeAxis.current = void 0;
    }, []);
    var scrollWheel = T$1(function(event) {
      shouldCancel(event.type, getDeltaXY(event), event.target, shouldCancelEvent(event, props.lockRef.current));
    }, []);
    var scrollTouchMove = T$1(function(event) {
      shouldCancel(event.type, getTouchXY(event), event.target, shouldCancelEvent(event, props.lockRef.current));
    }, []);
    p(function() {
      lockStack.push(Style2);
      props.setCallbacks({
        onScrollCapture: scrollWheel,
        onWheelCapture: scrollWheel,
        onTouchMoveCapture: scrollTouchMove
      });
      document.addEventListener("wheel", shouldPrevent, nonPassive);
      document.addEventListener("touchmove", shouldPrevent, nonPassive);
      document.addEventListener("touchstart", scrollTouchStart, nonPassive);
      return function() {
        lockStack = lockStack.filter(function(inst) {
          return inst !== Style2;
        });
        document.removeEventListener("wheel", shouldPrevent, nonPassive);
        document.removeEventListener("touchmove", shouldPrevent, nonPassive);
        document.removeEventListener("touchstart", scrollTouchStart, nonPassive);
      };
    }, []);
    var removeScrollBar = props.removeScrollBar, inert = props.inert;
    return y$1(
      k$2,
      null,
      inert ? y$1(Style2, { styles: generateStyle(id) }) : null,
      removeScrollBar ? y$1(RemoveScrollBar, { gapMode: "margin" }) : null
    );
  }
  const SideCar = exportSidecar(effectCar, RemoveScrollSideCar);
  var ReactRemoveScroll = k(function(props, ref2) {
    return y$1(RemoveScroll, __assign({}, props, { ref: ref2, sideCar: SideCar }));
  });
  ReactRemoveScroll.classNames = RemoveScroll.classNames;
  const $67UHm$RemoveScroll = ReactRemoveScroll;
  var getDefaultParent = function(originalTarget) {
    if (typeof document === "undefined") {
      return null;
    }
    var sampleTarget = Array.isArray(originalTarget) ? originalTarget[0] : originalTarget;
    return sampleTarget.ownerDocument.body;
  };
  var counterMap = /* @__PURE__ */ new WeakMap();
  var uncontrolledNodes = /* @__PURE__ */ new WeakMap();
  var markerMap = {};
  var lockCount = 0;
  var unwrapHost = function(node) {
    return node && (node.host || unwrapHost(node.parentNode));
  };
  var correctTargets = function(parent, targets) {
    return targets.map(function(target) {
      if (parent.contains(target)) {
        return target;
      }
      var correctedTarget = unwrapHost(target);
      if (correctedTarget && parent.contains(correctedTarget)) {
        return correctedTarget;
      }
      console.error("aria-hidden", target, "in not contained inside", parent, ". Doing nothing");
      return null;
    }).filter(function(x2) {
      return Boolean(x2);
    });
  };
  var applyAttributeToOthers = function(originalTarget, parentNode, markerName, controlAttribute) {
    var targets = correctTargets(parentNode, Array.isArray(originalTarget) ? originalTarget : [originalTarget]);
    if (!markerMap[markerName]) {
      markerMap[markerName] = /* @__PURE__ */ new WeakMap();
    }
    var markerCounter = markerMap[markerName];
    var hiddenNodes = [];
    var elementsToKeep = /* @__PURE__ */ new Set();
    var elementsToStop = new Set(targets);
    var keep = function(el) {
      if (!el || elementsToKeep.has(el)) {
        return;
      }
      elementsToKeep.add(el);
      keep(el.parentNode);
    };
    targets.forEach(keep);
    var deep = function(parent) {
      if (!parent || elementsToStop.has(parent)) {
        return;
      }
      Array.prototype.forEach.call(parent.children, function(node) {
        if (elementsToKeep.has(node)) {
          deep(node);
        } else {
          var attr = node.getAttribute(controlAttribute);
          var alreadyHidden = attr !== null && attr !== "false";
          var counterValue = (counterMap.get(node) || 0) + 1;
          var markerValue = (markerCounter.get(node) || 0) + 1;
          counterMap.set(node, counterValue);
          markerCounter.set(node, markerValue);
          hiddenNodes.push(node);
          if (counterValue === 1 && alreadyHidden) {
            uncontrolledNodes.set(node, true);
          }
          if (markerValue === 1) {
            node.setAttribute(markerName, "true");
          }
          if (!alreadyHidden) {
            node.setAttribute(controlAttribute, "true");
          }
        }
      });
    };
    deep(parentNode);
    elementsToKeep.clear();
    lockCount++;
    return function() {
      hiddenNodes.forEach(function(node) {
        var counterValue = counterMap.get(node) - 1;
        var markerValue = markerCounter.get(node) - 1;
        counterMap.set(node, counterValue);
        markerCounter.set(node, markerValue);
        if (!counterValue) {
          if (!uncontrolledNodes.has(node)) {
            node.removeAttribute(controlAttribute);
          }
          uncontrolledNodes.delete(node);
        }
        if (!markerValue) {
          node.removeAttribute(markerName);
        }
      });
      lockCount--;
      if (!lockCount) {
        counterMap = /* @__PURE__ */ new WeakMap();
        counterMap = /* @__PURE__ */ new WeakMap();
        uncontrolledNodes = /* @__PURE__ */ new WeakMap();
        markerMap = {};
      }
    };
  };
  var hideOthers = function(originalTarget, parentNode, markerName) {
    if (markerName === void 0) {
      markerName = "data-aria-hidden";
    }
    var targets = Array.from(Array.isArray(originalTarget) ? originalTarget : [originalTarget]);
    var activeParentNode = parentNode || getDefaultParent(originalTarget);
    if (!activeParentNode) {
      return function() {
        return null;
      };
    }
    targets.push.apply(targets, Array.from(activeParentNode.querySelectorAll("[aria-live]")));
    return applyAttributeToOthers(targets, activeParentNode, markerName, "aria-hidden");
  };
  const $5d3850c4d0b4e6c7$var$DIALOG_NAME = "Dialog";
  const [$5d3850c4d0b4e6c7$var$createDialogContext, $5d3850c4d0b4e6c7$export$cc702773b8ea3e41] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($5d3850c4d0b4e6c7$var$DIALOG_NAME);
  const [$5d3850c4d0b4e6c7$var$DialogProvider, $5d3850c4d0b4e6c7$var$useDialogContext] = $5d3850c4d0b4e6c7$var$createDialogContext($5d3850c4d0b4e6c7$var$DIALOG_NAME);
  const $5d3850c4d0b4e6c7$export$3ddf2d174ce01153 = (props) => {
    const { __scopeDialog, children, open: openProp, defaultOpen, onOpenChange, modal = true } = props;
    const triggerRef = _$2(null);
    const contentRef = _$2(null);
    const [open = false, setOpen] = $71cd76cc60e0454e$export$6f32135080cb4c3({
      prop: openProp,
      defaultProp: defaultOpen,
      onChange: onOpenChange
    });
    return /* @__PURE__ */ y$1($5d3850c4d0b4e6c7$var$DialogProvider, {
      scope: __scopeDialog,
      triggerRef,
      contentRef,
      contentId: $1746a345f3d73bb7$export$f680877a34711e37(),
      titleId: $1746a345f3d73bb7$export$f680877a34711e37(),
      descriptionId: $1746a345f3d73bb7$export$f680877a34711e37(),
      open,
      onOpenChange: setOpen,
      onOpenToggle: T$1(
        () => setOpen(
          (prevOpen) => !prevOpen
        ),
        [
          setOpen
        ]
      ),
      modal
    }, children);
  };
  const $5d3850c4d0b4e6c7$var$PORTAL_NAME = "DialogPortal";
  const [$5d3850c4d0b4e6c7$var$PortalProvider, $5d3850c4d0b4e6c7$var$usePortalContext] = $5d3850c4d0b4e6c7$var$createDialogContext($5d3850c4d0b4e6c7$var$PORTAL_NAME, {
    forceMount: void 0
  });
  const $5d3850c4d0b4e6c7$export$dad7c95542bacce0 = (props) => {
    const { __scopeDialog, forceMount, children, container } = props;
    const context = $5d3850c4d0b4e6c7$var$useDialogContext($5d3850c4d0b4e6c7$var$PORTAL_NAME, __scopeDialog);
    return /* @__PURE__ */ y$1($5d3850c4d0b4e6c7$var$PortalProvider, {
      scope: __scopeDialog,
      forceMount
    }, O.map(
      children,
      (child2) => /* @__PURE__ */ y$1($921a889cee6df7e8$export$99c2b779aa4e8b8b, {
        present: forceMount || context.open
      }, /* @__PURE__ */ y$1($f1701beae083dbae$export$602eac185826482c, {
        asChild: true,
        container
      }, child2))
    ));
  };
  const $5d3850c4d0b4e6c7$var$OVERLAY_NAME = "DialogOverlay";
  const $5d3850c4d0b4e6c7$export$bd1d06c79be19e17 = /* @__PURE__ */ k((props, forwardedRef) => {
    const portalContext = $5d3850c4d0b4e6c7$var$usePortalContext($5d3850c4d0b4e6c7$var$OVERLAY_NAME, props.__scopeDialog);
    const { forceMount = portalContext.forceMount, ...overlayProps } = props;
    const context = $5d3850c4d0b4e6c7$var$useDialogContext($5d3850c4d0b4e6c7$var$OVERLAY_NAME, props.__scopeDialog);
    return context.modal ? /* @__PURE__ */ y$1($921a889cee6df7e8$export$99c2b779aa4e8b8b, {
      present: forceMount || context.open
    }, /* @__PURE__ */ y$1($5d3850c4d0b4e6c7$var$DialogOverlayImpl, _extends({}, overlayProps, {
      ref: forwardedRef
    }))) : null;
  });
  const $5d3850c4d0b4e6c7$var$DialogOverlayImpl = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeDialog, ...overlayProps } = props;
    const context = $5d3850c4d0b4e6c7$var$useDialogContext($5d3850c4d0b4e6c7$var$OVERLAY_NAME, __scopeDialog);
    return (
      // Make sure `Content` is scrollable even when it doesn't live inside `RemoveScroll`
      // ie. when `Overlay` and `Content` are siblings
      /* @__PURE__ */ y$1($67UHm$RemoveScroll, {
        as: $5e63c961fc1ce211$export$8c6ed5c666ac1360,
        allowPinchZoom: true,
        shards: [
          context.contentRef
        ]
      }, /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends({
        "data-state": $5d3850c4d0b4e6c7$var$getState(context.open)
      }, overlayProps, {
        ref: forwardedRef,
        style: {
          pointerEvents: "auto",
          ...overlayProps.style
        }
      })))
    );
  });
  const $5d3850c4d0b4e6c7$var$CONTENT_NAME = "DialogContent";
  const $5d3850c4d0b4e6c7$export$b6d9565de1e068cf = /* @__PURE__ */ k((props, forwardedRef) => {
    const portalContext = $5d3850c4d0b4e6c7$var$usePortalContext($5d3850c4d0b4e6c7$var$CONTENT_NAME, props.__scopeDialog);
    const { forceMount = portalContext.forceMount, ...contentProps } = props;
    const context = $5d3850c4d0b4e6c7$var$useDialogContext($5d3850c4d0b4e6c7$var$CONTENT_NAME, props.__scopeDialog);
    return /* @__PURE__ */ y$1($921a889cee6df7e8$export$99c2b779aa4e8b8b, {
      present: forceMount || context.open
    }, context.modal ? /* @__PURE__ */ y$1($5d3850c4d0b4e6c7$var$DialogContentModal, _extends({}, contentProps, {
      ref: forwardedRef
    })) : /* @__PURE__ */ y$1($5d3850c4d0b4e6c7$var$DialogContentNonModal, _extends({}, contentProps, {
      ref: forwardedRef
    })));
  });
  const $5d3850c4d0b4e6c7$var$DialogContentModal = /* @__PURE__ */ k((props, forwardedRef) => {
    const context = $5d3850c4d0b4e6c7$var$useDialogContext($5d3850c4d0b4e6c7$var$CONTENT_NAME, props.__scopeDialog);
    const contentRef = _$2(null);
    const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, context.contentRef, contentRef);
    p(() => {
      const content = contentRef.current;
      if (content)
        return hideOthers(content);
    }, []);
    return /* @__PURE__ */ y$1($5d3850c4d0b4e6c7$var$DialogContentImpl, _extends({}, props, {
      ref: composedRefs,
      trapFocus: context.open,
      disableOutsidePointerEvents: true,
      onCloseAutoFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onCloseAutoFocus, (event) => {
        var _context$triggerRef$c;
        event.preventDefault();
        (_context$triggerRef$c = context.triggerRef.current) === null || _context$triggerRef$c === void 0 || _context$triggerRef$c.focus();
      }),
      onPointerDownOutside: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerDownOutside, (event) => {
        const originalEvent = event.detail.originalEvent;
        const ctrlLeftClick = originalEvent.button === 0 && originalEvent.ctrlKey === true;
        const isRightClick = originalEvent.button === 2 || ctrlLeftClick;
        if (isRightClick)
          event.preventDefault();
      }),
      onFocusOutside: $e42e1063c40fb3ef$export$b9ecd428b558ff10(
        props.onFocusOutside,
        (event) => event.preventDefault()
      )
    }));
  });
  const $5d3850c4d0b4e6c7$var$DialogContentNonModal = /* @__PURE__ */ k((props, forwardedRef) => {
    const context = $5d3850c4d0b4e6c7$var$useDialogContext($5d3850c4d0b4e6c7$var$CONTENT_NAME, props.__scopeDialog);
    const hasInteractedOutsideRef = _$2(false);
    const hasPointerDownOutsideRef = _$2(false);
    return /* @__PURE__ */ y$1($5d3850c4d0b4e6c7$var$DialogContentImpl, _extends({}, props, {
      ref: forwardedRef,
      trapFocus: false,
      disableOutsidePointerEvents: false,
      onCloseAutoFocus: (event) => {
        var _props$onCloseAutoFoc;
        (_props$onCloseAutoFoc = props.onCloseAutoFocus) === null || _props$onCloseAutoFoc === void 0 || _props$onCloseAutoFoc.call(props, event);
        if (!event.defaultPrevented) {
          var _context$triggerRef$c2;
          if (!hasInteractedOutsideRef.current)
            (_context$triggerRef$c2 = context.triggerRef.current) === null || _context$triggerRef$c2 === void 0 || _context$triggerRef$c2.focus();
          event.preventDefault();
        }
        hasInteractedOutsideRef.current = false;
        hasPointerDownOutsideRef.current = false;
      },
      onInteractOutside: (event) => {
        var _props$onInteractOuts, _context$triggerRef$c3;
        (_props$onInteractOuts = props.onInteractOutside) === null || _props$onInteractOuts === void 0 || _props$onInteractOuts.call(props, event);
        if (!event.defaultPrevented) {
          hasInteractedOutsideRef.current = true;
          if (event.detail.originalEvent.type === "pointerdown")
            hasPointerDownOutsideRef.current = true;
        }
        const target = event.target;
        const targetIsTrigger = (_context$triggerRef$c3 = context.triggerRef.current) === null || _context$triggerRef$c3 === void 0 ? void 0 : _context$triggerRef$c3.contains(target);
        if (targetIsTrigger)
          event.preventDefault();
        if (event.detail.originalEvent.type === "focusin" && hasPointerDownOutsideRef.current)
          event.preventDefault();
      }
    }));
  });
  const $5d3850c4d0b4e6c7$var$DialogContentImpl = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeDialog, trapFocus, onOpenAutoFocus, onCloseAutoFocus, ...contentProps } = props;
    const context = $5d3850c4d0b4e6c7$var$useDialogContext($5d3850c4d0b4e6c7$var$CONTENT_NAME, __scopeDialog);
    const contentRef = _$2(null);
    const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, contentRef);
    $3db38b7d1fb3fe6a$export$b7ece24a22aeda8c();
    return /* @__PURE__ */ y$1(k$2, null, /* @__PURE__ */ y$1($d3863c46a17e8a28$export$20e40289641fbbb6, {
      asChild: true,
      loop: true,
      trapped: trapFocus,
      onMountAutoFocus: onOpenAutoFocus,
      onUnmountAutoFocus: onCloseAutoFocus
    }, /* @__PURE__ */ y$1($5cb92bef7577960e$export$177fb62ff3ec1f22, _extends({
      role: "dialog",
      id: context.contentId,
      "aria-describedby": context.descriptionId,
      "aria-labelledby": context.titleId,
      "data-state": $5d3850c4d0b4e6c7$var$getState(context.open)
    }, contentProps, {
      ref: composedRefs,
      onDismiss: () => context.onOpenChange(false)
    }))), false);
  });
  const $5d3850c4d0b4e6c7$var$TITLE_NAME = "DialogTitle";
  const $5d3850c4d0b4e6c7$export$16f7638e4a34b909 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeDialog, ...titleProps } = props;
    const context = $5d3850c4d0b4e6c7$var$useDialogContext($5d3850c4d0b4e6c7$var$TITLE_NAME, __scopeDialog);
    return /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.h2, _extends({
      id: context.titleId
    }, titleProps, {
      ref: forwardedRef
    }));
  });
  const $5d3850c4d0b4e6c7$var$DESCRIPTION_NAME = "DialogDescription";
  const $5d3850c4d0b4e6c7$export$94e94c2ec2c954d5 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeDialog, ...descriptionProps } = props;
    const context = $5d3850c4d0b4e6c7$var$useDialogContext($5d3850c4d0b4e6c7$var$DESCRIPTION_NAME, __scopeDialog);
    return /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.p, _extends({
      id: context.descriptionId
    }, descriptionProps, {
      ref: forwardedRef
    }));
  });
  function $5d3850c4d0b4e6c7$var$getState(open) {
    return open ? "open" : "closed";
  }
  const $5d3850c4d0b4e6c7$export$be92b6f5f03c0fe9 = $5d3850c4d0b4e6c7$export$3ddf2d174ce01153;
  const $5d3850c4d0b4e6c7$export$602eac185826482c = $5d3850c4d0b4e6c7$export$dad7c95542bacce0;
  const $5d3850c4d0b4e6c7$export$c6fdb837b070b4ff = $5d3850c4d0b4e6c7$export$bd1d06c79be19e17;
  const $5d3850c4d0b4e6c7$export$7c6e2c02157bb7d2 = $5d3850c4d0b4e6c7$export$b6d9565de1e068cf;
  const $5d3850c4d0b4e6c7$export$f99233281efd08a0 = $5d3850c4d0b4e6c7$export$16f7638e4a34b909;
  const $5d3850c4d0b4e6c7$export$393edc798c47379d = $5d3850c4d0b4e6c7$export$94e94c2ec2c954d5;
  const CustomSelectionSaveDialogue = () => {
    var _a2;
    const notificationContext = q$1(NotificationContext);
    const sectionSelectionContext = q$1(SectionSelectionContext);
    const onSubmitCloseDialogueAndSaveSettings = (event) => {
      var _a3;
      event.stopPropagation();
      event.preventDefault();
      const chosenNameState = (_a3 = document.getElementById(DIALOGUE_SAVE_CUSTOM_SELECTION_NAME_ID)) == null ? void 0 : _a3.value;
      if (!chosenNameState || chosenNameState.length === 0) {
        notificationContext.setOptions({
          type: NotificationType.ERROR,
          timeout: 1e4,
          title: instance.t(`${LANG_NS_MAIN}:pageExerciseSaveDialogueErrorGeneralTitle`),
          text: instance.t(`${LANG_NS_MAIN}:pageExerciseSaveDialogueErrorNoNameText`)
        });
        sectionSelectionContext.setDialogueSaveSelectionsClosed();
        return;
      }
      sectionSelectionContext.setInCustomSelectionsExercisesStorage({
        exerciseID: sectionSelectionContext.selectedExercise.exerciseID,
        exerciseTitle: sectionSelectionContext.selectedExercise.exerciseTitle
      });
      sectionSelectionContext.setInCustomSelectionsStorage({
        name: chosenNameState,
        exerciseID: sectionSelectionContext.selectedExercise.exerciseID,
        exerciseTitle: sectionSelectionContext.selectedExercise.exerciseTitle,
        sections: sectionSelectionContext.selectedSections
      });
      sectionSelectionContext.setDialogueSaveSelectionsClosed();
    };
    return o($5d3850c4d0b4e6c7$export$be92b6f5f03c0fe9, {
      open: sectionSelectionContext.dialogueSaveSelectionsOpen,
      children: o($5d3850c4d0b4e6c7$export$602eac185826482c, {
        children: [o($5d3850c4d0b4e6c7$export$c6fdb837b070b4ff, {
          className: "DialogOverlay"
        }), o($5d3850c4d0b4e6c7$export$7c6e2c02157bb7d2, {
          className: "DialogContent",
          children: [o($5d3850c4d0b4e6c7$export$f99233281efd08a0, {
            className: "DialogTitle",
            children: instance.t(`${LANG_NS_MAIN}:pageExerciseSaveDialogueTitle`)
          }), o("form", {
            target: "#",
            onSubmit: onSubmitCloseDialogueAndSaveSettings,
            children: [o("div", {
              className: "DialogContentScroll",
              children: [o($5d3850c4d0b4e6c7$export$393edc798c47379d, {
                className: "DialogDescription",
                children: instance.t(`${LANG_NS_MAIN}:pageExerciseSaveDialogueGeneralDescription`)
              }), o("fieldset", {
                className: "Fieldset",
                children: [o("label", {
                  className: "Label",
                  htmlFor: DIALOGUE_SAVE_CUSTOM_SELECTION_NAME_ID,
                  children: instance.t(`${LANG_NS_MAIN}:pageExerciseSaveDialogueName`)
                }), o("input", {
                  className: "Input",
                  id: DIALOGUE_SAVE_CUSTOM_SELECTION_NAME_ID,
                  required: true,
                  value: (_a2 = sectionSelectionContext.selectionStorageMatch) == null ? void 0 : _a2.name
                })]
              })]
            }), o("div", {
              className: "ButtonGroup",
              children: o("button", {
                className: "Button green",
                type: "submit",
                children: instance.t(`${LANG_NS_MAIN}:save`)
              })
            }), o("button", {
              className: "IconButton",
              "aria-label": "Close",
              onClick: sectionSelectionContext.setDialogueSaveSelectionsClosed,
              children: o(Cross2Icon, {})
            })]
          })]
        })]
      })
    });
  };
  function useCombinedRefs() {
    for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) {
      refs[_key] = arguments[_key];
    }
    return F$1(
      () => (node) => {
        refs.forEach((ref2) => ref2(node));
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      refs
    );
  }
  const canUseDOM = typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined";
  function isWindow(element) {
    const elementString = Object.prototype.toString.call(element);
    return elementString === "[object Window]" || // In Electron context the Window object serializes to [object global]
    elementString === "[object global]";
  }
  function isNode(node) {
    return "nodeType" in node;
  }
  function getWindow(target) {
    var _target$ownerDocument, _target$ownerDocument2;
    if (!target) {
      return window;
    }
    if (isWindow(target)) {
      return target;
    }
    if (!isNode(target)) {
      return window;
    }
    return (_target$ownerDocument = (_target$ownerDocument2 = target.ownerDocument) == null ? void 0 : _target$ownerDocument2.defaultView) != null ? _target$ownerDocument : window;
  }
  function isDocument(node) {
    const {
      Document
    } = getWindow(node);
    return node instanceof Document;
  }
  function isHTMLElement(node) {
    if (isWindow(node)) {
      return false;
    }
    return node instanceof getWindow(node).HTMLElement;
  }
  function isSVGElement(node) {
    return node instanceof getWindow(node).SVGElement;
  }
  function getOwnerDocument(target) {
    if (!target) {
      return document;
    }
    if (isWindow(target)) {
      return target.document;
    }
    if (!isNode(target)) {
      return document;
    }
    if (isDocument(target)) {
      return target;
    }
    if (isHTMLElement(target)) {
      return target.ownerDocument;
    }
    return document;
  }
  const useIsomorphicLayoutEffect = canUseDOM ? y : p;
  function useEvent(handler) {
    const handlerRef = _$2(handler);
    useIsomorphicLayoutEffect(() => {
      handlerRef.current = handler;
    });
    return T$1(function() {
      for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
        args[_key] = arguments[_key];
      }
      return handlerRef.current == null ? void 0 : handlerRef.current(...args);
    }, []);
  }
  function useInterval() {
    const intervalRef = _$2(null);
    const set2 = T$1((listener, duration) => {
      intervalRef.current = setInterval(listener, duration);
    }, []);
    const clear = T$1(() => {
      if (intervalRef.current !== null) {
        clearInterval(intervalRef.current);
        intervalRef.current = null;
      }
    }, []);
    return [set2, clear];
  }
  function useLatestValue(value, dependencies) {
    if (dependencies === void 0) {
      dependencies = [value];
    }
    const valueRef = _$2(value);
    useIsomorphicLayoutEffect(() => {
      if (valueRef.current !== value) {
        valueRef.current = value;
      }
    }, dependencies);
    return valueRef;
  }
  function useLazyMemo(callback, dependencies) {
    const valueRef = _$2();
    return F$1(
      () => {
        const newValue = callback(valueRef.current);
        valueRef.current = newValue;
        return newValue;
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [...dependencies]
    );
  }
  function useNodeRef(onChange) {
    const onChangeHandler = useEvent(onChange);
    const node = _$2(null);
    const setNodeRef = T$1(
      (element) => {
        if (element !== node.current) {
          onChangeHandler == null ? void 0 : onChangeHandler(element, node.current);
        }
        node.current = element;
      },
      //eslint-disable-next-line
      []
    );
    return [node, setNodeRef];
  }
  function usePrevious(value) {
    const ref2 = _$2();
    p(() => {
      ref2.current = value;
    }, [value]);
    return ref2.current;
  }
  let ids = {};
  function useUniqueId(prefix, value) {
    return F$1(() => {
      if (value) {
        return value;
      }
      const id = ids[prefix] == null ? 0 : ids[prefix] + 1;
      ids[prefix] = id;
      return prefix + "-" + id;
    }, [prefix, value]);
  }
  function createAdjustmentFn(modifier) {
    return function(object) {
      for (var _len = arguments.length, adjustments = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        adjustments[_key - 1] = arguments[_key];
      }
      return adjustments.reduce((accumulator, adjustment) => {
        const entries = Object.entries(adjustment);
        for (const [key, valueAdjustment] of entries) {
          const value = accumulator[key];
          if (value != null) {
            accumulator[key] = value + modifier * valueAdjustment;
          }
        }
        return accumulator;
      }, {
        ...object
      });
    };
  }
  const add = /* @__PURE__ */ createAdjustmentFn(1);
  const subtract = /* @__PURE__ */ createAdjustmentFn(-1);
  function hasViewportRelativeCoordinates(event) {
    return "clientX" in event && "clientY" in event;
  }
  function isKeyboardEvent(event) {
    if (!event) {
      return false;
    }
    const {
      KeyboardEvent
    } = getWindow(event.target);
    return KeyboardEvent && event instanceof KeyboardEvent;
  }
  function isTouchEvent(event) {
    if (!event) {
      return false;
    }
    const {
      TouchEvent
    } = getWindow(event.target);
    return TouchEvent && event instanceof TouchEvent;
  }
  function getEventCoordinates(event) {
    if (isTouchEvent(event)) {
      if (event.touches && event.touches.length) {
        const {
          clientX: x2,
          clientY: y2
        } = event.touches[0];
        return {
          x: x2,
          y: y2
        };
      } else if (event.changedTouches && event.changedTouches.length) {
        const {
          clientX: x2,
          clientY: y2
        } = event.changedTouches[0];
        return {
          x: x2,
          y: y2
        };
      }
    }
    if (hasViewportRelativeCoordinates(event)) {
      return {
        x: event.clientX,
        y: event.clientY
      };
    }
    return null;
  }
  const CSS = /* @__PURE__ */ Object.freeze({
    Translate: {
      toString(transform) {
        if (!transform) {
          return;
        }
        const {
          x: x2,
          y: y2
        } = transform;
        return "translate3d(" + (x2 ? Math.round(x2) : 0) + "px, " + (y2 ? Math.round(y2) : 0) + "px, 0)";
      }
    },
    Scale: {
      toString(transform) {
        if (!transform) {
          return;
        }
        const {
          scaleX,
          scaleY
        } = transform;
        return "scaleX(" + scaleX + ") scaleY(" + scaleY + ")";
      }
    },
    Transform: {
      toString(transform) {
        if (!transform) {
          return;
        }
        return [CSS.Translate.toString(transform), CSS.Scale.toString(transform)].join(" ");
      }
    },
    Transition: {
      toString(_ref) {
        let {
          property,
          duration,
          easing
        } = _ref;
        return property + " " + duration + "ms " + easing;
      }
    }
  });
  const SELECTOR = "a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";
  function findFirstFocusableNode(element) {
    if (element.matches(SELECTOR)) {
      return element;
    }
    return element.querySelector(SELECTOR);
  }
  const hiddenStyles = {
    display: "none"
  };
  function HiddenText(_ref) {
    let {
      id,
      value
    } = _ref;
    return Cn.createElement("div", {
      id,
      style: hiddenStyles
    }, value);
  }
  const visuallyHidden = {
    position: "fixed",
    width: 1,
    height: 1,
    margin: -1,
    border: 0,
    padding: 0,
    overflow: "hidden",
    clip: "rect(0 0 0 0)",
    clipPath: "inset(100%)",
    whiteSpace: "nowrap"
  };
  function LiveRegion(_ref) {
    let {
      id,
      announcement
    } = _ref;
    return Cn.createElement("div", {
      id,
      style: visuallyHidden,
      role: "status",
      "aria-live": "assertive",
      "aria-atomic": true
    }, announcement);
  }
  function useAnnouncement() {
    const [announcement, setAnnouncement] = h("");
    const announce = T$1((value) => {
      if (value != null) {
        setAnnouncement(value);
      }
    }, []);
    return {
      announce,
      announcement
    };
  }
  const DndMonitorContext = /* @__PURE__ */ G$1(null);
  function useDndMonitor(listener) {
    const registerListener = q$1(DndMonitorContext);
    p(() => {
      if (!registerListener) {
        throw new Error("useDndMonitor must be used within a children of <DndContext>");
      }
      const unsubscribe = registerListener(listener);
      return unsubscribe;
    }, [listener, registerListener]);
  }
  function useDndMonitorProvider() {
    const [listeners] = h(() => /* @__PURE__ */ new Set());
    const registerListener = T$1((listener) => {
      listeners.add(listener);
      return () => listeners.delete(listener);
    }, [listeners]);
    const dispatch = T$1((_ref) => {
      let {
        type,
        event
      } = _ref;
      listeners.forEach((listener) => {
        var _listener$type;
        return (_listener$type = listener[type]) == null ? void 0 : _listener$type.call(listener, event);
      });
    }, [listeners]);
    return [dispatch, registerListener];
  }
  const defaultScreenReaderInstructions = {
    draggable: "\n    To pick up a draggable item, press the space bar.\n    While dragging, use the arrow keys to move the item.\n    Press space again to drop the item in its new position, or press escape to cancel.\n  "
  };
  const defaultAnnouncements = {
    onDragStart(_ref) {
      let {
        active
      } = _ref;
      return "Picked up draggable item " + active.id + ".";
    },
    onDragOver(_ref2) {
      let {
        active,
        over
      } = _ref2;
      if (over) {
        return "Draggable item " + active.id + " was moved over droppable area " + over.id + ".";
      }
      return "Draggable item " + active.id + " is no longer over a droppable area.";
    },
    onDragEnd(_ref3) {
      let {
        active,
        over
      } = _ref3;
      if (over) {
        return "Draggable item " + active.id + " was dropped over droppable area " + over.id;
      }
      return "Draggable item " + active.id + " was dropped.";
    },
    onDragCancel(_ref4) {
      let {
        active
      } = _ref4;
      return "Dragging was cancelled. Draggable item " + active.id + " was dropped.";
    }
  };
  function Accessibility(_ref) {
    let {
      announcements = defaultAnnouncements,
      container,
      hiddenTextDescribedById,
      screenReaderInstructions = defaultScreenReaderInstructions
    } = _ref;
    const {
      announce,
      announcement
    } = useAnnouncement();
    const liveRegionId = useUniqueId("DndLiveRegion");
    const [mounted, setMounted] = h(false);
    p(() => {
      setMounted(true);
    }, []);
    useDndMonitor(F$1(() => ({
      onDragStart(_ref2) {
        let {
          active
        } = _ref2;
        announce(announcements.onDragStart({
          active
        }));
      },
      onDragMove(_ref3) {
        let {
          active,
          over
        } = _ref3;
        if (announcements.onDragMove) {
          announce(announcements.onDragMove({
            active,
            over
          }));
        }
      },
      onDragOver(_ref4) {
        let {
          active,
          over
        } = _ref4;
        announce(announcements.onDragOver({
          active,
          over
        }));
      },
      onDragEnd(_ref5) {
        let {
          active,
          over
        } = _ref5;
        announce(announcements.onDragEnd({
          active,
          over
        }));
      },
      onDragCancel(_ref6) {
        let {
          active,
          over
        } = _ref6;
        announce(announcements.onDragCancel({
          active,
          over
        }));
      }
    }), [announce, announcements]));
    if (!mounted) {
      return null;
    }
    const markup = Cn.createElement(Cn.Fragment, null, Cn.createElement(HiddenText, {
      id: hiddenTextDescribedById,
      value: screenReaderInstructions.draggable
    }), Cn.createElement(LiveRegion, {
      id: liveRegionId,
      announcement
    }));
    return container ? z(markup, container) : markup;
  }
  var Action;
  (function(Action2) {
    Action2["DragStart"] = "dragStart";
    Action2["DragMove"] = "dragMove";
    Action2["DragEnd"] = "dragEnd";
    Action2["DragCancel"] = "dragCancel";
    Action2["DragOver"] = "dragOver";
    Action2["RegisterDroppable"] = "registerDroppable";
    Action2["SetDroppableDisabled"] = "setDroppableDisabled";
    Action2["UnregisterDroppable"] = "unregisterDroppable";
  })(Action || (Action = {}));
  function noop() {
  }
  function useSensor(sensor, options) {
    return F$1(
      () => ({
        sensor,
        options: options != null ? options : {}
      }),
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [sensor, options]
    );
  }
  function useSensors() {
    for (var _len = arguments.length, sensors = new Array(_len), _key = 0; _key < _len; _key++) {
      sensors[_key] = arguments[_key];
    }
    return F$1(
      () => [...sensors].filter((sensor) => sensor != null),
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [...sensors]
    );
  }
  const defaultCoordinates = /* @__PURE__ */ Object.freeze({
    x: 0,
    y: 0
  });
  function distanceBetween(p1, p2) {
    return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
  }
  function sortCollisionsAsc(_ref, _ref2) {
    let {
      data: {
        value: a2
      }
    } = _ref;
    let {
      data: {
        value: b2
      }
    } = _ref2;
    return a2 - b2;
  }
  function sortCollisionsDesc(_ref3, _ref4) {
    let {
      data: {
        value: a2
      }
    } = _ref3;
    let {
      data: {
        value: b2
      }
    } = _ref4;
    return b2 - a2;
  }
  function cornersOfRectangle(_ref5) {
    let {
      left,
      top,
      height,
      width
    } = _ref5;
    return [{
      x: left,
      y: top
    }, {
      x: left + width,
      y: top
    }, {
      x: left,
      y: top + height
    }, {
      x: left + width,
      y: top + height
    }];
  }
  function getFirstCollision(collisions, property) {
    if (!collisions || collisions.length === 0) {
      return null;
    }
    const [firstCollision] = collisions;
    return property ? firstCollision[property] : firstCollision;
  }
  function centerOfRectangle(rect, left, top) {
    if (left === void 0) {
      left = rect.left;
    }
    if (top === void 0) {
      top = rect.top;
    }
    return {
      x: left + rect.width * 0.5,
      y: top + rect.height * 0.5
    };
  }
  const closestCenter = (_ref) => {
    let {
      collisionRect,
      droppableRects,
      droppableContainers
    } = _ref;
    const centerRect = centerOfRectangle(collisionRect, collisionRect.left, collisionRect.top);
    const collisions = [];
    for (const droppableContainer of droppableContainers) {
      const {
        id
      } = droppableContainer;
      const rect = droppableRects.get(id);
      if (rect) {
        const distBetween = distanceBetween(centerOfRectangle(rect), centerRect);
        collisions.push({
          id,
          data: {
            droppableContainer,
            value: distBetween
          }
        });
      }
    }
    return collisions.sort(sortCollisionsAsc);
  };
  const closestCorners = (_ref) => {
    let {
      collisionRect,
      droppableRects,
      droppableContainers
    } = _ref;
    const corners = cornersOfRectangle(collisionRect);
    const collisions = [];
    for (const droppableContainer of droppableContainers) {
      const {
        id
      } = droppableContainer;
      const rect = droppableRects.get(id);
      if (rect) {
        const rectCorners = cornersOfRectangle(rect);
        const distances = corners.reduce((accumulator, corner, index2) => {
          return accumulator + distanceBetween(rectCorners[index2], corner);
        }, 0);
        const effectiveDistance = Number((distances / 4).toFixed(4));
        collisions.push({
          id,
          data: {
            droppableContainer,
            value: effectiveDistance
          }
        });
      }
    }
    return collisions.sort(sortCollisionsAsc);
  };
  function getIntersectionRatio(entry, target) {
    const top = Math.max(target.top, entry.top);
    const left = Math.max(target.left, entry.left);
    const right = Math.min(target.left + target.width, entry.left + entry.width);
    const bottom = Math.min(target.top + target.height, entry.top + entry.height);
    const width = right - left;
    const height = bottom - top;
    if (left < right && top < bottom) {
      const targetArea = target.width * target.height;
      const entryArea = entry.width * entry.height;
      const intersectionArea = width * height;
      const intersectionRatio = intersectionArea / (targetArea + entryArea - intersectionArea);
      return Number(intersectionRatio.toFixed(4));
    }
    return 0;
  }
  const rectIntersection = (_ref) => {
    let {
      collisionRect,
      droppableRects,
      droppableContainers
    } = _ref;
    const collisions = [];
    for (const droppableContainer of droppableContainers) {
      const {
        id
      } = droppableContainer;
      const rect = droppableRects.get(id);
      if (rect) {
        const intersectionRatio = getIntersectionRatio(rect, collisionRect);
        if (intersectionRatio > 0) {
          collisions.push({
            id,
            data: {
              droppableContainer,
              value: intersectionRatio
            }
          });
        }
      }
    }
    return collisions.sort(sortCollisionsDesc);
  };
  function adjustScale(transform, rect1, rect2) {
    return {
      ...transform,
      scaleX: rect1 && rect2 ? rect1.width / rect2.width : 1,
      scaleY: rect1 && rect2 ? rect1.height / rect2.height : 1
    };
  }
  function getRectDelta(rect1, rect2) {
    return rect1 && rect2 ? {
      x: rect1.left - rect2.left,
      y: rect1.top - rect2.top
    } : defaultCoordinates;
  }
  function createRectAdjustmentFn(modifier) {
    return function adjustClientRect(rect) {
      for (var _len = arguments.length, adjustments = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
        adjustments[_key - 1] = arguments[_key];
      }
      return adjustments.reduce((acc, adjustment) => ({
        ...acc,
        top: acc.top + modifier * adjustment.y,
        bottom: acc.bottom + modifier * adjustment.y,
        left: acc.left + modifier * adjustment.x,
        right: acc.right + modifier * adjustment.x
      }), {
        ...rect
      });
    };
  }
  const getAdjustedRect = /* @__PURE__ */ createRectAdjustmentFn(1);
  function parseTransform(transform) {
    if (transform.startsWith("matrix3d(")) {
      const transformArray = transform.slice(9, -1).split(/, /);
      return {
        x: +transformArray[12],
        y: +transformArray[13],
        scaleX: +transformArray[0],
        scaleY: +transformArray[5]
      };
    } else if (transform.startsWith("matrix(")) {
      const transformArray = transform.slice(7, -1).split(/, /);
      return {
        x: +transformArray[4],
        y: +transformArray[5],
        scaleX: +transformArray[0],
        scaleY: +transformArray[3]
      };
    }
    return null;
  }
  function inverseTransform(rect, transform, transformOrigin) {
    const parsedTransform = parseTransform(transform);
    if (!parsedTransform) {
      return rect;
    }
    const {
      scaleX,
      scaleY,
      x: translateX,
      y: translateY
    } = parsedTransform;
    const x2 = rect.left - translateX - (1 - scaleX) * parseFloat(transformOrigin);
    const y2 = rect.top - translateY - (1 - scaleY) * parseFloat(transformOrigin.slice(transformOrigin.indexOf(" ") + 1));
    const w2 = scaleX ? rect.width / scaleX : rect.width;
    const h2 = scaleY ? rect.height / scaleY : rect.height;
    return {
      width: w2,
      height: h2,
      top: y2,
      right: x2 + w2,
      bottom: y2 + h2,
      left: x2
    };
  }
  const defaultOptions = {
    ignoreTransform: false
  };
  function getClientRect(element, options) {
    if (options === void 0) {
      options = defaultOptions;
    }
    let rect = element.getBoundingClientRect();
    if (options.ignoreTransform) {
      const {
        transform,
        transformOrigin
      } = getWindow(element).getComputedStyle(element);
      if (transform) {
        rect = inverseTransform(rect, transform, transformOrigin);
      }
    }
    const {
      top,
      left,
      width,
      height,
      bottom,
      right
    } = rect;
    return {
      top,
      left,
      width,
      height,
      bottom,
      right
    };
  }
  function getTransformAgnosticClientRect(element) {
    return getClientRect(element, {
      ignoreTransform: true
    });
  }
  function getWindowClientRect(element) {
    const width = element.innerWidth;
    const height = element.innerHeight;
    return {
      top: 0,
      left: 0,
      right: width,
      bottom: height,
      width,
      height
    };
  }
  function isFixed(node, computedStyle) {
    if (computedStyle === void 0) {
      computedStyle = getWindow(node).getComputedStyle(node);
    }
    return computedStyle.position === "fixed";
  }
  function isScrollable(element, computedStyle) {
    if (computedStyle === void 0) {
      computedStyle = getWindow(element).getComputedStyle(element);
    }
    const overflowRegex = /(auto|scroll|overlay)/;
    const properties2 = ["overflow", "overflowX", "overflowY"];
    return properties2.some((property) => {
      const value = computedStyle[property];
      return typeof value === "string" ? overflowRegex.test(value) : false;
    });
  }
  function getScrollableAncestors(element, limit) {
    const scrollParents = [];
    function findScrollableAncestors(node) {
      if (limit != null && scrollParents.length >= limit) {
        return scrollParents;
      }
      if (!node) {
        return scrollParents;
      }
      if (isDocument(node) && node.scrollingElement != null && !scrollParents.includes(node.scrollingElement)) {
        scrollParents.push(node.scrollingElement);
        return scrollParents;
      }
      if (!isHTMLElement(node) || isSVGElement(node)) {
        return scrollParents;
      }
      if (scrollParents.includes(node)) {
        return scrollParents;
      }
      const computedStyle = getWindow(element).getComputedStyle(node);
      if (node !== element) {
        if (isScrollable(node, computedStyle)) {
          scrollParents.push(node);
        }
      }
      if (isFixed(node, computedStyle)) {
        return scrollParents;
      }
      return findScrollableAncestors(node.parentNode);
    }
    if (!element) {
      return scrollParents;
    }
    return findScrollableAncestors(element);
  }
  function getFirstScrollableAncestor(node) {
    const [firstScrollableAncestor] = getScrollableAncestors(node, 1);
    return firstScrollableAncestor != null ? firstScrollableAncestor : null;
  }
  function getScrollableElement(element) {
    if (!canUseDOM || !element) {
      return null;
    }
    if (isWindow(element)) {
      return element;
    }
    if (!isNode(element)) {
      return null;
    }
    if (isDocument(element) || element === getOwnerDocument(element).scrollingElement) {
      return window;
    }
    if (isHTMLElement(element)) {
      return element;
    }
    return null;
  }
  function getScrollXCoordinate(element) {
    if (isWindow(element)) {
      return element.scrollX;
    }
    return element.scrollLeft;
  }
  function getScrollYCoordinate(element) {
    if (isWindow(element)) {
      return element.scrollY;
    }
    return element.scrollTop;
  }
  function getScrollCoordinates(element) {
    return {
      x: getScrollXCoordinate(element),
      y: getScrollYCoordinate(element)
    };
  }
  var Direction;
  (function(Direction2) {
    Direction2[Direction2["Forward"] = 1] = "Forward";
    Direction2[Direction2["Backward"] = -1] = "Backward";
  })(Direction || (Direction = {}));
  function isDocumentScrollingElement(element) {
    if (!canUseDOM || !element) {
      return false;
    }
    return element === document.scrollingElement;
  }
  function getScrollPosition(scrollingContainer) {
    const minScroll = {
      x: 0,
      y: 0
    };
    const dimensions = isDocumentScrollingElement(scrollingContainer) ? {
      height: window.innerHeight,
      width: window.innerWidth
    } : {
      height: scrollingContainer.clientHeight,
      width: scrollingContainer.clientWidth
    };
    const maxScroll = {
      x: scrollingContainer.scrollWidth - dimensions.width,
      y: scrollingContainer.scrollHeight - dimensions.height
    };
    const isTop = scrollingContainer.scrollTop <= minScroll.y;
    const isLeft = scrollingContainer.scrollLeft <= minScroll.x;
    const isBottom = scrollingContainer.scrollTop >= maxScroll.y;
    const isRight = scrollingContainer.scrollLeft >= maxScroll.x;
    return {
      isTop,
      isLeft,
      isBottom,
      isRight,
      maxScroll,
      minScroll
    };
  }
  const defaultThreshold = {
    x: 0.2,
    y: 0.2
  };
  function getScrollDirectionAndSpeed(scrollContainer, scrollContainerRect, _ref, acceleration, thresholdPercentage) {
    let {
      top,
      left,
      right,
      bottom
    } = _ref;
    if (acceleration === void 0) {
      acceleration = 10;
    }
    if (thresholdPercentage === void 0) {
      thresholdPercentage = defaultThreshold;
    }
    const {
      isTop,
      isBottom,
      isLeft,
      isRight
    } = getScrollPosition(scrollContainer);
    const direction = {
      x: 0,
      y: 0
    };
    const speed = {
      x: 0,
      y: 0
    };
    const threshold = {
      height: scrollContainerRect.height * thresholdPercentage.y,
      width: scrollContainerRect.width * thresholdPercentage.x
    };
    if (!isTop && top <= scrollContainerRect.top + threshold.height) {
      direction.y = Direction.Backward;
      speed.y = acceleration * Math.abs((scrollContainerRect.top + threshold.height - top) / threshold.height);
    } else if (!isBottom && bottom >= scrollContainerRect.bottom - threshold.height) {
      direction.y = Direction.Forward;
      speed.y = acceleration * Math.abs((scrollContainerRect.bottom - threshold.height - bottom) / threshold.height);
    }
    if (!isRight && right >= scrollContainerRect.right - threshold.width) {
      direction.x = Direction.Forward;
      speed.x = acceleration * Math.abs((scrollContainerRect.right - threshold.width - right) / threshold.width);
    } else if (!isLeft && left <= scrollContainerRect.left + threshold.width) {
      direction.x = Direction.Backward;
      speed.x = acceleration * Math.abs((scrollContainerRect.left + threshold.width - left) / threshold.width);
    }
    return {
      direction,
      speed
    };
  }
  function getScrollElementRect(element) {
    if (element === document.scrollingElement) {
      const {
        innerWidth,
        innerHeight
      } = window;
      return {
        top: 0,
        left: 0,
        right: innerWidth,
        bottom: innerHeight,
        width: innerWidth,
        height: innerHeight
      };
    }
    const {
      top,
      left,
      right,
      bottom
    } = element.getBoundingClientRect();
    return {
      top,
      left,
      right,
      bottom,
      width: element.clientWidth,
      height: element.clientHeight
    };
  }
  function getScrollOffsets(scrollableAncestors) {
    return scrollableAncestors.reduce((acc, node) => {
      return add(acc, getScrollCoordinates(node));
    }, defaultCoordinates);
  }
  function getScrollXOffset(scrollableAncestors) {
    return scrollableAncestors.reduce((acc, node) => {
      return acc + getScrollXCoordinate(node);
    }, 0);
  }
  function getScrollYOffset(scrollableAncestors) {
    return scrollableAncestors.reduce((acc, node) => {
      return acc + getScrollYCoordinate(node);
    }, 0);
  }
  function scrollIntoViewIfNeeded(element, measure) {
    if (measure === void 0) {
      measure = getClientRect;
    }
    if (!element) {
      return;
    }
    const {
      top,
      left,
      bottom,
      right
    } = measure(element);
    const firstScrollableAncestor = getFirstScrollableAncestor(element);
    if (!firstScrollableAncestor) {
      return;
    }
    if (bottom <= 0 || right <= 0 || top >= window.innerHeight || left >= window.innerWidth) {
      element.scrollIntoView({
        block: "center",
        inline: "center"
      });
    }
  }
  const properties = [["x", ["left", "right"], getScrollXOffset], ["y", ["top", "bottom"], getScrollYOffset]];
  class Rect {
    constructor(rect, element) {
      this.rect = void 0;
      this.width = void 0;
      this.height = void 0;
      this.top = void 0;
      this.bottom = void 0;
      this.right = void 0;
      this.left = void 0;
      const scrollableAncestors = getScrollableAncestors(element);
      const scrollOffsets = getScrollOffsets(scrollableAncestors);
      this.rect = {
        ...rect
      };
      this.width = rect.width;
      this.height = rect.height;
      for (const [axis, keys, getScrollOffset] of properties) {
        for (const key of keys) {
          Object.defineProperty(this, key, {
            get: () => {
              const currentOffsets = getScrollOffset(scrollableAncestors);
              const scrollOffsetsDeltla = scrollOffsets[axis] - currentOffsets;
              return this.rect[key] + scrollOffsetsDeltla;
            },
            enumerable: true
          });
        }
      }
      Object.defineProperty(this, "rect", {
        enumerable: false
      });
    }
  }
  class Listeners {
    constructor(target) {
      this.target = void 0;
      this.listeners = [];
      this.removeAll = () => {
        this.listeners.forEach((listener) => {
          var _this$target;
          return (_this$target = this.target) == null ? void 0 : _this$target.removeEventListener(...listener);
        });
      };
      this.target = target;
    }
    add(eventName, handler, options) {
      var _this$target2;
      (_this$target2 = this.target) == null ? void 0 : _this$target2.addEventListener(eventName, handler, options);
      this.listeners.push([eventName, handler, options]);
    }
  }
  function getEventListenerTarget(target) {
    const {
      EventTarget
    } = getWindow(target);
    return target instanceof EventTarget ? target : getOwnerDocument(target);
  }
  function hasExceededDistance(delta, measurement) {
    const dx = Math.abs(delta.x);
    const dy = Math.abs(delta.y);
    if (typeof measurement === "number") {
      return Math.sqrt(dx ** 2 + dy ** 2) > measurement;
    }
    if ("x" in measurement && "y" in measurement) {
      return dx > measurement.x && dy > measurement.y;
    }
    if ("x" in measurement) {
      return dx > measurement.x;
    }
    if ("y" in measurement) {
      return dy > measurement.y;
    }
    return false;
  }
  var EventName;
  (function(EventName2) {
    EventName2["Click"] = "click";
    EventName2["DragStart"] = "dragstart";
    EventName2["Keydown"] = "keydown";
    EventName2["ContextMenu"] = "contextmenu";
    EventName2["Resize"] = "resize";
    EventName2["SelectionChange"] = "selectionchange";
    EventName2["VisibilityChange"] = "visibilitychange";
  })(EventName || (EventName = {}));
  function preventDefault(event) {
    event.preventDefault();
  }
  function stopPropagation(event) {
    event.stopPropagation();
  }
  var KeyboardCode;
  (function(KeyboardCode2) {
    KeyboardCode2["Space"] = "Space";
    KeyboardCode2["Down"] = "ArrowDown";
    KeyboardCode2["Right"] = "ArrowRight";
    KeyboardCode2["Left"] = "ArrowLeft";
    KeyboardCode2["Up"] = "ArrowUp";
    KeyboardCode2["Esc"] = "Escape";
    KeyboardCode2["Enter"] = "Enter";
  })(KeyboardCode || (KeyboardCode = {}));
  const defaultKeyboardCodes = {
    start: [KeyboardCode.Space, KeyboardCode.Enter],
    cancel: [KeyboardCode.Esc],
    end: [KeyboardCode.Space, KeyboardCode.Enter]
  };
  const defaultKeyboardCoordinateGetter = (event, _ref) => {
    let {
      currentCoordinates
    } = _ref;
    switch (event.code) {
      case KeyboardCode.Right:
        return {
          ...currentCoordinates,
          x: currentCoordinates.x + 25
        };
      case KeyboardCode.Left:
        return {
          ...currentCoordinates,
          x: currentCoordinates.x - 25
        };
      case KeyboardCode.Down:
        return {
          ...currentCoordinates,
          y: currentCoordinates.y + 25
        };
      case KeyboardCode.Up:
        return {
          ...currentCoordinates,
          y: currentCoordinates.y - 25
        };
    }
    return void 0;
  };
  class KeyboardSensor {
    constructor(props) {
      this.props = void 0;
      this.autoScrollEnabled = false;
      this.referenceCoordinates = void 0;
      this.listeners = void 0;
      this.windowListeners = void 0;
      this.props = props;
      const {
        event: {
          target
        }
      } = props;
      this.props = props;
      this.listeners = new Listeners(getOwnerDocument(target));
      this.windowListeners = new Listeners(getWindow(target));
      this.handleKeyDown = this.handleKeyDown.bind(this);
      this.handleCancel = this.handleCancel.bind(this);
      this.attach();
    }
    attach() {
      this.handleStart();
      this.windowListeners.add(EventName.Resize, this.handleCancel);
      this.windowListeners.add(EventName.VisibilityChange, this.handleCancel);
      setTimeout(() => this.listeners.add(EventName.Keydown, this.handleKeyDown));
    }
    handleStart() {
      const {
        activeNode,
        onStart
      } = this.props;
      const node = activeNode.node.current;
      if (node) {
        scrollIntoViewIfNeeded(node);
      }
      onStart(defaultCoordinates);
    }
    handleKeyDown(event) {
      if (isKeyboardEvent(event)) {
        const {
          active,
          context,
          options
        } = this.props;
        const {
          keyboardCodes = defaultKeyboardCodes,
          coordinateGetter = defaultKeyboardCoordinateGetter,
          scrollBehavior = "smooth"
        } = options;
        const {
          code
        } = event;
        if (keyboardCodes.end.includes(code)) {
          this.handleEnd(event);
          return;
        }
        if (keyboardCodes.cancel.includes(code)) {
          this.handleCancel(event);
          return;
        }
        const {
          collisionRect
        } = context.current;
        const currentCoordinates = collisionRect ? {
          x: collisionRect.left,
          y: collisionRect.top
        } : defaultCoordinates;
        if (!this.referenceCoordinates) {
          this.referenceCoordinates = currentCoordinates;
        }
        const newCoordinates = coordinateGetter(event, {
          active,
          context: context.current,
          currentCoordinates
        });
        if (newCoordinates) {
          const coordinatesDelta = subtract(newCoordinates, currentCoordinates);
          const scrollDelta = {
            x: 0,
            y: 0
          };
          const {
            scrollableAncestors
          } = context.current;
          for (const scrollContainer of scrollableAncestors) {
            const direction = event.code;
            const {
              isTop,
              isRight,
              isLeft,
              isBottom,
              maxScroll,
              minScroll
            } = getScrollPosition(scrollContainer);
            const scrollElementRect = getScrollElementRect(scrollContainer);
            const clampedCoordinates = {
              x: Math.min(direction === KeyboardCode.Right ? scrollElementRect.right - scrollElementRect.width / 2 : scrollElementRect.right, Math.max(direction === KeyboardCode.Right ? scrollElementRect.left : scrollElementRect.left + scrollElementRect.width / 2, newCoordinates.x)),
              y: Math.min(direction === KeyboardCode.Down ? scrollElementRect.bottom - scrollElementRect.height / 2 : scrollElementRect.bottom, Math.max(direction === KeyboardCode.Down ? scrollElementRect.top : scrollElementRect.top + scrollElementRect.height / 2, newCoordinates.y))
            };
            const canScrollX = direction === KeyboardCode.Right && !isRight || direction === KeyboardCode.Left && !isLeft;
            const canScrollY = direction === KeyboardCode.Down && !isBottom || direction === KeyboardCode.Up && !isTop;
            if (canScrollX && clampedCoordinates.x !== newCoordinates.x) {
              const newScrollCoordinates = scrollContainer.scrollLeft + coordinatesDelta.x;
              const canScrollToNewCoordinates = direction === KeyboardCode.Right && newScrollCoordinates <= maxScroll.x || direction === KeyboardCode.Left && newScrollCoordinates >= minScroll.x;
              if (canScrollToNewCoordinates && !coordinatesDelta.y) {
                scrollContainer.scrollTo({
                  left: newScrollCoordinates,
                  behavior: scrollBehavior
                });
                return;
              }
              if (canScrollToNewCoordinates) {
                scrollDelta.x = scrollContainer.scrollLeft - newScrollCoordinates;
              } else {
                scrollDelta.x = direction === KeyboardCode.Right ? scrollContainer.scrollLeft - maxScroll.x : scrollContainer.scrollLeft - minScroll.x;
              }
              if (scrollDelta.x) {
                scrollContainer.scrollBy({
                  left: -scrollDelta.x,
                  behavior: scrollBehavior
                });
              }
              break;
            } else if (canScrollY && clampedCoordinates.y !== newCoordinates.y) {
              const newScrollCoordinates = scrollContainer.scrollTop + coordinatesDelta.y;
              const canScrollToNewCoordinates = direction === KeyboardCode.Down && newScrollCoordinates <= maxScroll.y || direction === KeyboardCode.Up && newScrollCoordinates >= minScroll.y;
              if (canScrollToNewCoordinates && !coordinatesDelta.x) {
                scrollContainer.scrollTo({
                  top: newScrollCoordinates,
                  behavior: scrollBehavior
                });
                return;
              }
              if (canScrollToNewCoordinates) {
                scrollDelta.y = scrollContainer.scrollTop - newScrollCoordinates;
              } else {
                scrollDelta.y = direction === KeyboardCode.Down ? scrollContainer.scrollTop - maxScroll.y : scrollContainer.scrollTop - minScroll.y;
              }
              if (scrollDelta.y) {
                scrollContainer.scrollBy({
                  top: -scrollDelta.y,
                  behavior: scrollBehavior
                });
              }
              break;
            }
          }
          this.handleMove(event, add(subtract(newCoordinates, this.referenceCoordinates), scrollDelta));
        }
      }
    }
    handleMove(event, coordinates) {
      const {
        onMove
      } = this.props;
      event.preventDefault();
      onMove(coordinates);
    }
    handleEnd(event) {
      const {
        onEnd
      } = this.props;
      event.preventDefault();
      this.detach();
      onEnd();
    }
    handleCancel(event) {
      const {
        onCancel
      } = this.props;
      event.preventDefault();
      this.detach();
      onCancel();
    }
    detach() {
      this.listeners.removeAll();
      this.windowListeners.removeAll();
    }
  }
  KeyboardSensor.activators = [{
    eventName: "onKeyDown",
    handler: (event, _ref, _ref2) => {
      let {
        keyboardCodes = defaultKeyboardCodes,
        onActivation
      } = _ref;
      let {
        active
      } = _ref2;
      const {
        code
      } = event.nativeEvent;
      if (keyboardCodes.start.includes(code)) {
        const activator = active.activatorNode.current;
        if (activator && event.target !== activator) {
          return false;
        }
        event.preventDefault();
        onActivation == null ? void 0 : onActivation({
          event: event.nativeEvent
        });
        return true;
      }
      return false;
    }
  }];
  function isDistanceConstraint(constraint) {
    return Boolean(constraint && "distance" in constraint);
  }
  function isDelayConstraint(constraint) {
    return Boolean(constraint && "delay" in constraint);
  }
  class AbstractPointerSensor {
    constructor(props, events2, listenerTarget) {
      var _getEventCoordinates;
      if (listenerTarget === void 0) {
        listenerTarget = getEventListenerTarget(props.event.target);
      }
      this.props = void 0;
      this.events = void 0;
      this.autoScrollEnabled = true;
      this.document = void 0;
      this.activated = false;
      this.initialCoordinates = void 0;
      this.timeoutId = null;
      this.listeners = void 0;
      this.documentListeners = void 0;
      this.windowListeners = void 0;
      this.props = props;
      this.events = events2;
      const {
        event
      } = props;
      const {
        target
      } = event;
      this.props = props;
      this.events = events2;
      this.document = getOwnerDocument(target);
      this.documentListeners = new Listeners(this.document);
      this.listeners = new Listeners(listenerTarget);
      this.windowListeners = new Listeners(getWindow(target));
      this.initialCoordinates = (_getEventCoordinates = getEventCoordinates(event)) != null ? _getEventCoordinates : defaultCoordinates;
      this.handleStart = this.handleStart.bind(this);
      this.handleMove = this.handleMove.bind(this);
      this.handleEnd = this.handleEnd.bind(this);
      this.handleCancel = this.handleCancel.bind(this);
      this.handleKeydown = this.handleKeydown.bind(this);
      this.removeTextSelection = this.removeTextSelection.bind(this);
      this.attach();
    }
    attach() {
      const {
        events: events2,
        props: {
          options: {
            activationConstraint
          }
        }
      } = this;
      this.listeners.add(events2.move.name, this.handleMove, {
        passive: false
      });
      this.listeners.add(events2.end.name, this.handleEnd);
      this.windowListeners.add(EventName.Resize, this.handleCancel);
      this.windowListeners.add(EventName.DragStart, preventDefault);
      this.windowListeners.add(EventName.VisibilityChange, this.handleCancel);
      this.windowListeners.add(EventName.ContextMenu, preventDefault);
      this.documentListeners.add(EventName.Keydown, this.handleKeydown);
      if (activationConstraint) {
        if (isDistanceConstraint(activationConstraint)) {
          return;
        }
        if (isDelayConstraint(activationConstraint)) {
          this.timeoutId = setTimeout(this.handleStart, activationConstraint.delay);
          return;
        }
      }
      this.handleStart();
    }
    detach() {
      this.listeners.removeAll();
      this.windowListeners.removeAll();
      setTimeout(this.documentListeners.removeAll, 50);
      if (this.timeoutId !== null) {
        clearTimeout(this.timeoutId);
        this.timeoutId = null;
      }
    }
    handleStart() {
      const {
        initialCoordinates
      } = this;
      const {
        onStart
      } = this.props;
      if (initialCoordinates) {
        this.activated = true;
        this.documentListeners.add(EventName.Click, stopPropagation, {
          capture: true
        });
        this.removeTextSelection();
        this.documentListeners.add(EventName.SelectionChange, this.removeTextSelection);
        onStart(initialCoordinates);
      }
    }
    handleMove(event) {
      var _getEventCoordinates2;
      const {
        activated,
        initialCoordinates,
        props
      } = this;
      const {
        onMove,
        options: {
          activationConstraint
        }
      } = props;
      if (!initialCoordinates) {
        return;
      }
      const coordinates = (_getEventCoordinates2 = getEventCoordinates(event)) != null ? _getEventCoordinates2 : defaultCoordinates;
      const delta = subtract(initialCoordinates, coordinates);
      if (!activated && activationConstraint) {
        if (isDelayConstraint(activationConstraint)) {
          if (hasExceededDistance(delta, activationConstraint.tolerance)) {
            return this.handleCancel();
          }
          return;
        }
        if (isDistanceConstraint(activationConstraint)) {
          if (activationConstraint.tolerance != null && hasExceededDistance(delta, activationConstraint.tolerance)) {
            return this.handleCancel();
          }
          if (hasExceededDistance(delta, activationConstraint.distance)) {
            return this.handleStart();
          }
          return;
        }
      }
      if (event.cancelable) {
        event.preventDefault();
      }
      onMove(coordinates);
    }
    handleEnd() {
      const {
        onEnd
      } = this.props;
      this.detach();
      onEnd();
    }
    handleCancel() {
      const {
        onCancel
      } = this.props;
      this.detach();
      onCancel();
    }
    handleKeydown(event) {
      if (event.code === KeyboardCode.Esc) {
        this.handleCancel();
      }
    }
    removeTextSelection() {
      var _this$document$getSel;
      (_this$document$getSel = this.document.getSelection()) == null ? void 0 : _this$document$getSel.removeAllRanges();
    }
  }
  const events = {
    move: {
      name: "pointermove"
    },
    end: {
      name: "pointerup"
    }
  };
  class PointerSensor extends AbstractPointerSensor {
    constructor(props) {
      const {
        event
      } = props;
      const listenerTarget = getOwnerDocument(event.target);
      super(props, events, listenerTarget);
    }
  }
  PointerSensor.activators = [{
    eventName: "onPointerDown",
    handler: (_ref, _ref2) => {
      let {
        nativeEvent: event
      } = _ref;
      let {
        onActivation
      } = _ref2;
      if (!event.isPrimary || event.button !== 0) {
        return false;
      }
      onActivation == null ? void 0 : onActivation({
        event
      });
      return true;
    }
  }];
  const events$1 = {
    move: {
      name: "mousemove"
    },
    end: {
      name: "mouseup"
    }
  };
  var MouseButton;
  (function(MouseButton2) {
    MouseButton2[MouseButton2["RightClick"] = 2] = "RightClick";
  })(MouseButton || (MouseButton = {}));
  class MouseSensor extends AbstractPointerSensor {
    constructor(props) {
      super(props, events$1, getOwnerDocument(props.event.target));
    }
  }
  MouseSensor.activators = [{
    eventName: "onMouseDown",
    handler: (_ref, _ref2) => {
      let {
        nativeEvent: event
      } = _ref;
      let {
        onActivation
      } = _ref2;
      if (event.button === MouseButton.RightClick) {
        return false;
      }
      onActivation == null ? void 0 : onActivation({
        event
      });
      return true;
    }
  }];
  const events$2 = {
    move: {
      name: "touchmove"
    },
    end: {
      name: "touchend"
    }
  };
  class TouchSensor extends AbstractPointerSensor {
    constructor(props) {
      super(props, events$2);
    }
    static setup() {
      window.addEventListener(events$2.move.name, noop2, {
        capture: false,
        passive: false
      });
      return function teardown() {
        window.removeEventListener(events$2.move.name, noop2);
      };
      function noop2() {
      }
    }
  }
  TouchSensor.activators = [{
    eventName: "onTouchStart",
    handler: (_ref, _ref2) => {
      let {
        nativeEvent: event
      } = _ref;
      let {
        onActivation
      } = _ref2;
      const {
        touches
      } = event;
      if (touches.length > 1) {
        return false;
      }
      onActivation == null ? void 0 : onActivation({
        event
      });
      return true;
    }
  }];
  var AutoScrollActivator;
  (function(AutoScrollActivator2) {
    AutoScrollActivator2[AutoScrollActivator2["Pointer"] = 0] = "Pointer";
    AutoScrollActivator2[AutoScrollActivator2["DraggableRect"] = 1] = "DraggableRect";
  })(AutoScrollActivator || (AutoScrollActivator = {}));
  var TraversalOrder;
  (function(TraversalOrder2) {
    TraversalOrder2[TraversalOrder2["TreeOrder"] = 0] = "TreeOrder";
    TraversalOrder2[TraversalOrder2["ReversedTreeOrder"] = 1] = "ReversedTreeOrder";
  })(TraversalOrder || (TraversalOrder = {}));
  function useAutoScroller(_ref) {
    let {
      acceleration,
      activator = AutoScrollActivator.Pointer,
      canScroll,
      draggingRect,
      enabled,
      interval = 5,
      order = TraversalOrder.TreeOrder,
      pointerCoordinates,
      scrollableAncestors,
      scrollableAncestorRects,
      delta,
      threshold
    } = _ref;
    const scrollIntent = useScrollIntent({
      delta,
      disabled: !enabled
    });
    const [setAutoScrollInterval, clearAutoScrollInterval] = useInterval();
    const scrollSpeed = _$2({
      x: 0,
      y: 0
    });
    const scrollDirection = _$2({
      x: 0,
      y: 0
    });
    const rect = F$1(() => {
      switch (activator) {
        case AutoScrollActivator.Pointer:
          return pointerCoordinates ? {
            top: pointerCoordinates.y,
            bottom: pointerCoordinates.y,
            left: pointerCoordinates.x,
            right: pointerCoordinates.x
          } : null;
        case AutoScrollActivator.DraggableRect:
          return draggingRect;
      }
    }, [activator, draggingRect, pointerCoordinates]);
    const scrollContainerRef = _$2(null);
    const autoScroll = T$1(() => {
      const scrollContainer = scrollContainerRef.current;
      if (!scrollContainer) {
        return;
      }
      const scrollLeft = scrollSpeed.current.x * scrollDirection.current.x;
      const scrollTop = scrollSpeed.current.y * scrollDirection.current.y;
      scrollContainer.scrollBy(scrollLeft, scrollTop);
    }, []);
    const sortedScrollableAncestors = F$1(() => order === TraversalOrder.TreeOrder ? [...scrollableAncestors].reverse() : scrollableAncestors, [order, scrollableAncestors]);
    p(
      () => {
        if (!enabled || !scrollableAncestors.length || !rect) {
          clearAutoScrollInterval();
          return;
        }
        for (const scrollContainer of sortedScrollableAncestors) {
          if ((canScroll == null ? void 0 : canScroll(scrollContainer)) === false) {
            continue;
          }
          const index2 = scrollableAncestors.indexOf(scrollContainer);
          const scrollContainerRect = scrollableAncestorRects[index2];
          if (!scrollContainerRect) {
            continue;
          }
          const {
            direction,
            speed
          } = getScrollDirectionAndSpeed(scrollContainer, scrollContainerRect, rect, acceleration, threshold);
          for (const axis of ["x", "y"]) {
            if (!scrollIntent[axis][direction[axis]]) {
              speed[axis] = 0;
              direction[axis] = 0;
            }
          }
          if (speed.x > 0 || speed.y > 0) {
            clearAutoScrollInterval();
            scrollContainerRef.current = scrollContainer;
            setAutoScrollInterval(autoScroll, interval);
            scrollSpeed.current = speed;
            scrollDirection.current = direction;
            return;
          }
        }
        scrollSpeed.current = {
          x: 0,
          y: 0
        };
        scrollDirection.current = {
          x: 0,
          y: 0
        };
        clearAutoScrollInterval();
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [
        acceleration,
        autoScroll,
        canScroll,
        clearAutoScrollInterval,
        enabled,
        interval,
        // eslint-disable-next-line react-hooks/exhaustive-deps
        JSON.stringify(rect),
        // eslint-disable-next-line react-hooks/exhaustive-deps
        JSON.stringify(scrollIntent),
        setAutoScrollInterval,
        scrollableAncestors,
        sortedScrollableAncestors,
        scrollableAncestorRects,
        // eslint-disable-next-line react-hooks/exhaustive-deps
        JSON.stringify(threshold)
      ]
    );
  }
  const defaultScrollIntent = {
    x: {
      [Direction.Backward]: false,
      [Direction.Forward]: false
    },
    y: {
      [Direction.Backward]: false,
      [Direction.Forward]: false
    }
  };
  function useScrollIntent(_ref2) {
    let {
      delta,
      disabled
    } = _ref2;
    const previousDelta = usePrevious(delta);
    return useLazyMemo((previousIntent) => {
      if (disabled || !previousDelta || !previousIntent) {
        return defaultScrollIntent;
      }
      const direction = {
        x: Math.sign(delta.x - previousDelta.x),
        y: Math.sign(delta.y - previousDelta.y)
      };
      return {
        x: {
          [Direction.Backward]: previousIntent.x[Direction.Backward] || direction.x === -1,
          [Direction.Forward]: previousIntent.x[Direction.Forward] || direction.x === 1
        },
        y: {
          [Direction.Backward]: previousIntent.y[Direction.Backward] || direction.y === -1,
          [Direction.Forward]: previousIntent.y[Direction.Forward] || direction.y === 1
        }
      };
    }, [disabled, delta, previousDelta]);
  }
  function useCachedNode(draggableNodes, id) {
    const draggableNode = id !== null ? draggableNodes.get(id) : void 0;
    const node = draggableNode ? draggableNode.node.current : null;
    return useLazyMemo((cachedNode) => {
      var _ref;
      if (id === null) {
        return null;
      }
      return (_ref = node != null ? node : cachedNode) != null ? _ref : null;
    }, [node, id]);
  }
  function useCombineActivators(sensors, getSyntheticHandler) {
    return F$1(() => sensors.reduce((accumulator, sensor) => {
      const {
        sensor: Sensor
      } = sensor;
      const sensorActivators = Sensor.activators.map((activator) => ({
        eventName: activator.eventName,
        handler: getSyntheticHandler(activator.handler, sensor)
      }));
      return [...accumulator, ...sensorActivators];
    }, []), [sensors, getSyntheticHandler]);
  }
  var MeasuringStrategy;
  (function(MeasuringStrategy2) {
    MeasuringStrategy2[MeasuringStrategy2["Always"] = 0] = "Always";
    MeasuringStrategy2[MeasuringStrategy2["BeforeDragging"] = 1] = "BeforeDragging";
    MeasuringStrategy2[MeasuringStrategy2["WhileDragging"] = 2] = "WhileDragging";
  })(MeasuringStrategy || (MeasuringStrategy = {}));
  var MeasuringFrequency;
  (function(MeasuringFrequency2) {
    MeasuringFrequency2["Optimized"] = "optimized";
  })(MeasuringFrequency || (MeasuringFrequency = {}));
  const defaultValue = /* @__PURE__ */ new Map();
  function useDroppableMeasuring(containers, _ref) {
    let {
      dragging,
      dependencies,
      config
    } = _ref;
    const [queue, setQueue] = h(null);
    const {
      frequency,
      measure,
      strategy
    } = config;
    const containersRef = _$2(containers);
    const disabled = isDisabled();
    const disabledRef = useLatestValue(disabled);
    const measureDroppableContainers = T$1(function(ids2) {
      if (ids2 === void 0) {
        ids2 = [];
      }
      if (disabledRef.current) {
        return;
      }
      setQueue((value) => {
        if (value === null) {
          return ids2;
        }
        return value.concat(ids2.filter((id) => !value.includes(id)));
      });
    }, [disabledRef]);
    const timeoutId = _$2(null);
    const droppableRects = useLazyMemo((previousValue) => {
      if (disabled && !dragging) {
        return defaultValue;
      }
      if (!previousValue || previousValue === defaultValue || containersRef.current !== containers || queue != null) {
        const map2 = /* @__PURE__ */ new Map();
        for (let container of containers) {
          if (!container) {
            continue;
          }
          if (queue && queue.length > 0 && !queue.includes(container.id) && container.rect.current) {
            map2.set(container.id, container.rect.current);
            continue;
          }
          const node = container.node.current;
          const rect = node ? new Rect(measure(node), node) : null;
          container.rect.current = rect;
          if (rect) {
            map2.set(container.id, rect);
          }
        }
        return map2;
      }
      return previousValue;
    }, [containers, queue, dragging, disabled, measure]);
    p(() => {
      containersRef.current = containers;
    }, [containers]);
    p(
      () => {
        if (disabled) {
          return;
        }
        measureDroppableContainers();
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [dragging, disabled]
    );
    p(
      () => {
        if (queue && queue.length > 0) {
          setQueue(null);
        }
      },
      //eslint-disable-next-line react-hooks/exhaustive-deps
      [JSON.stringify(queue)]
    );
    p(
      () => {
        if (disabled || typeof frequency !== "number" || timeoutId.current !== null) {
          return;
        }
        timeoutId.current = setTimeout(() => {
          measureDroppableContainers();
          timeoutId.current = null;
        }, frequency);
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [frequency, disabled, measureDroppableContainers, ...dependencies]
    );
    return {
      droppableRects,
      measureDroppableContainers,
      measuringScheduled: queue != null
    };
    function isDisabled() {
      switch (strategy) {
        case MeasuringStrategy.Always:
          return false;
        case MeasuringStrategy.BeforeDragging:
          return dragging;
        default:
          return !dragging;
      }
    }
  }
  function useInitialValue(value, computeFn) {
    return useLazyMemo((previousValue) => {
      if (!value) {
        return null;
      }
      if (previousValue) {
        return previousValue;
      }
      return typeof computeFn === "function" ? computeFn(value) : value;
    }, [computeFn, value]);
  }
  function useInitialRect(node, measure) {
    return useInitialValue(node, measure);
  }
  function useMutationObserver(_ref) {
    let {
      callback,
      disabled
    } = _ref;
    const handleMutations = useEvent(callback);
    const mutationObserver = F$1(() => {
      if (disabled || typeof window === "undefined" || typeof window.MutationObserver === "undefined") {
        return void 0;
      }
      const {
        MutationObserver: MutationObserver2
      } = window;
      return new MutationObserver2(handleMutations);
    }, [handleMutations, disabled]);
    p(() => {
      return () => mutationObserver == null ? void 0 : mutationObserver.disconnect();
    }, [mutationObserver]);
    return mutationObserver;
  }
  function useResizeObserver(_ref) {
    let {
      callback,
      disabled
    } = _ref;
    const handleResize = useEvent(callback);
    const resizeObserver = F$1(
      () => {
        if (disabled || typeof window === "undefined" || typeof window.ResizeObserver === "undefined") {
          return void 0;
        }
        const {
          ResizeObserver: ResizeObserver2
        } = window;
        return new ResizeObserver2(handleResize);
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [disabled]
    );
    p(() => {
      return () => resizeObserver == null ? void 0 : resizeObserver.disconnect();
    }, [resizeObserver]);
    return resizeObserver;
  }
  function defaultMeasure(element) {
    return new Rect(getClientRect(element), element);
  }
  function useRect(element, measure, fallbackRect) {
    if (measure === void 0) {
      measure = defaultMeasure;
    }
    const [rect, measureRect] = s(reducer2, null);
    const mutationObserver = useMutationObserver({
      callback(records) {
        if (!element) {
          return;
        }
        for (const record of records) {
          const {
            type,
            target
          } = record;
          if (type === "childList" && target instanceof HTMLElement && target.contains(element)) {
            measureRect();
            break;
          }
        }
      }
    });
    const resizeObserver = useResizeObserver({
      callback: measureRect
    });
    useIsomorphicLayoutEffect(() => {
      measureRect();
      if (element) {
        resizeObserver == null ? void 0 : resizeObserver.observe(element);
        mutationObserver == null ? void 0 : mutationObserver.observe(document.body, {
          childList: true,
          subtree: true
        });
      } else {
        resizeObserver == null ? void 0 : resizeObserver.disconnect();
        mutationObserver == null ? void 0 : mutationObserver.disconnect();
      }
    }, [element]);
    return rect;
    function reducer2(currentRect) {
      if (!element) {
        return null;
      }
      if (element.isConnected === false) {
        var _ref;
        return (_ref = currentRect != null ? currentRect : fallbackRect) != null ? _ref : null;
      }
      const newRect = measure(element);
      if (JSON.stringify(currentRect) === JSON.stringify(newRect)) {
        return currentRect;
      }
      return newRect;
    }
  }
  function useRectDelta(rect) {
    const initialRect = useInitialValue(rect);
    return getRectDelta(rect, initialRect);
  }
  const defaultValue$1 = [];
  function useScrollableAncestors(node) {
    const previousNode = _$2(node);
    const ancestors = useLazyMemo((previousValue) => {
      if (!node) {
        return defaultValue$1;
      }
      if (previousValue && previousValue !== defaultValue$1 && node && previousNode.current && node.parentNode === previousNode.current.parentNode) {
        return previousValue;
      }
      return getScrollableAncestors(node);
    }, [node]);
    p(() => {
      previousNode.current = node;
    }, [node]);
    return ancestors;
  }
  function useScrollOffsets(elements) {
    const [scrollCoordinates, setScrollCoordinates] = h(null);
    const prevElements = _$2(elements);
    const handleScroll2 = T$1((event) => {
      const scrollingElement = getScrollableElement(event.target);
      if (!scrollingElement) {
        return;
      }
      setScrollCoordinates((scrollCoordinates2) => {
        if (!scrollCoordinates2) {
          return null;
        }
        scrollCoordinates2.set(scrollingElement, getScrollCoordinates(scrollingElement));
        return new Map(scrollCoordinates2);
      });
    }, []);
    p(() => {
      const previousElements = prevElements.current;
      if (elements !== previousElements) {
        cleanup(previousElements);
        const entries = elements.map((element) => {
          const scrollableElement = getScrollableElement(element);
          if (scrollableElement) {
            scrollableElement.addEventListener("scroll", handleScroll2, {
              passive: true
            });
            return [scrollableElement, getScrollCoordinates(scrollableElement)];
          }
          return null;
        }).filter((entry) => entry != null);
        setScrollCoordinates(entries.length ? new Map(entries) : null);
        prevElements.current = elements;
      }
      return () => {
        cleanup(elements);
        cleanup(previousElements);
      };
      function cleanup(elements2) {
        elements2.forEach((element) => {
          const scrollableElement = getScrollableElement(element);
          scrollableElement == null ? void 0 : scrollableElement.removeEventListener("scroll", handleScroll2);
        });
      }
    }, [handleScroll2, elements]);
    return F$1(() => {
      if (elements.length) {
        return scrollCoordinates ? Array.from(scrollCoordinates.values()).reduce((acc, coordinates) => add(acc, coordinates), defaultCoordinates) : getScrollOffsets(elements);
      }
      return defaultCoordinates;
    }, [elements, scrollCoordinates]);
  }
  function useScrollOffsetsDelta(scrollOffsets, dependencies) {
    if (dependencies === void 0) {
      dependencies = [];
    }
    const initialScrollOffsets = _$2(null);
    p(
      () => {
        initialScrollOffsets.current = null;
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      dependencies
    );
    p(() => {
      const hasScrollOffsets = scrollOffsets !== defaultCoordinates;
      if (hasScrollOffsets && !initialScrollOffsets.current) {
        initialScrollOffsets.current = scrollOffsets;
      }
      if (!hasScrollOffsets && initialScrollOffsets.current) {
        initialScrollOffsets.current = null;
      }
    }, [scrollOffsets]);
    return initialScrollOffsets.current ? subtract(scrollOffsets, initialScrollOffsets.current) : defaultCoordinates;
  }
  function useSensorSetup(sensors) {
    p(
      () => {
        if (!canUseDOM) {
          return;
        }
        const teardownFns = sensors.map((_ref) => {
          let {
            sensor
          } = _ref;
          return sensor.setup == null ? void 0 : sensor.setup();
        });
        return () => {
          for (const teardown of teardownFns) {
            teardown == null ? void 0 : teardown();
          }
        };
      },
      // TO-DO: Sensors length could theoretically change which would not be a valid dependency
      // eslint-disable-next-line react-hooks/exhaustive-deps
      sensors.map((_ref2) => {
        let {
          sensor
        } = _ref2;
        return sensor;
      })
    );
  }
  function useSyntheticListeners(listeners, id) {
    return F$1(() => {
      return listeners.reduce((acc, _ref) => {
        let {
          eventName,
          handler
        } = _ref;
        acc[eventName] = (event) => {
          handler(event, id);
        };
        return acc;
      }, {});
    }, [listeners, id]);
  }
  function useWindowRect(element) {
    return F$1(() => element ? getWindowClientRect(element) : null, [element]);
  }
  const defaultValue$2 = [];
  function useRects(elements, measure) {
    if (measure === void 0) {
      measure = getClientRect;
    }
    const [firstElement] = elements;
    const windowRect = useWindowRect(firstElement ? getWindow(firstElement) : null);
    const [rects, measureRects] = s(reducer2, defaultValue$2);
    const resizeObserver = useResizeObserver({
      callback: measureRects
    });
    if (elements.length > 0 && rects === defaultValue$2) {
      measureRects();
    }
    useIsomorphicLayoutEffect(() => {
      if (elements.length) {
        elements.forEach((element) => resizeObserver == null ? void 0 : resizeObserver.observe(element));
      } else {
        resizeObserver == null ? void 0 : resizeObserver.disconnect();
        measureRects();
      }
    }, [elements]);
    return rects;
    function reducer2() {
      if (!elements.length) {
        return defaultValue$2;
      }
      return elements.map((element) => isDocumentScrollingElement(element) ? windowRect : new Rect(measure(element), element));
    }
  }
  function getMeasurableNode(node) {
    if (!node) {
      return null;
    }
    if (node.children.length > 1) {
      return node;
    }
    const firstChild = node.children[0];
    return isHTMLElement(firstChild) ? firstChild : node;
  }
  function useDragOverlayMeasuring(_ref) {
    let {
      measure
    } = _ref;
    const [rect, setRect] = h(null);
    const handleResize = T$1((entries) => {
      for (const {
        target
      } of entries) {
        if (isHTMLElement(target)) {
          setRect((rect2) => {
            const newRect = measure(target);
            return rect2 ? {
              ...rect2,
              width: newRect.width,
              height: newRect.height
            } : newRect;
          });
          break;
        }
      }
    }, [measure]);
    const resizeObserver = useResizeObserver({
      callback: handleResize
    });
    const handleNodeChange = T$1((element) => {
      const node = getMeasurableNode(element);
      resizeObserver == null ? void 0 : resizeObserver.disconnect();
      if (node) {
        resizeObserver == null ? void 0 : resizeObserver.observe(node);
      }
      setRect(node ? measure(node) : null);
    }, [measure, resizeObserver]);
    const [nodeRef, setRef] = useNodeRef(handleNodeChange);
    return F$1(() => ({
      nodeRef,
      rect,
      setRef
    }), [rect, nodeRef, setRef]);
  }
  const defaultSensors = [{
    sensor: PointerSensor,
    options: {}
  }, {
    sensor: KeyboardSensor,
    options: {}
  }];
  const defaultData = {
    current: {}
  };
  const defaultMeasuringConfiguration = {
    draggable: {
      measure: getTransformAgnosticClientRect
    },
    droppable: {
      measure: getTransformAgnosticClientRect,
      strategy: MeasuringStrategy.WhileDragging,
      frequency: MeasuringFrequency.Optimized
    },
    dragOverlay: {
      measure: getClientRect
    }
  };
  class DroppableContainersMap extends Map {
    get(id) {
      var _super$get;
      return id != null ? (_super$get = super.get(id)) != null ? _super$get : void 0 : void 0;
    }
    toArray() {
      return Array.from(this.values());
    }
    getEnabled() {
      return this.toArray().filter((_ref) => {
        let {
          disabled
        } = _ref;
        return !disabled;
      });
    }
    getNodeFor(id) {
      var _this$get$node$curren, _this$get;
      return (_this$get$node$curren = (_this$get = this.get(id)) == null ? void 0 : _this$get.node.current) != null ? _this$get$node$curren : void 0;
    }
  }
  const defaultPublicContext = {
    activatorEvent: null,
    active: null,
    activeNode: null,
    activeNodeRect: null,
    collisions: null,
    containerNodeRect: null,
    draggableNodes: /* @__PURE__ */ new Map(),
    droppableRects: /* @__PURE__ */ new Map(),
    droppableContainers: /* @__PURE__ */ new DroppableContainersMap(),
    over: null,
    dragOverlay: {
      nodeRef: {
        current: null
      },
      rect: null,
      setRef: noop
    },
    scrollableAncestors: [],
    scrollableAncestorRects: [],
    measuringConfiguration: defaultMeasuringConfiguration,
    measureDroppableContainers: noop,
    windowRect: null,
    measuringScheduled: false
  };
  const defaultInternalContext = {
    activatorEvent: null,
    activators: [],
    active: null,
    activeNodeRect: null,
    ariaDescribedById: {
      draggable: ""
    },
    dispatch: noop,
    draggableNodes: /* @__PURE__ */ new Map(),
    over: null,
    measureDroppableContainers: noop
  };
  const InternalContext = /* @__PURE__ */ G$1(defaultInternalContext);
  const PublicContext = /* @__PURE__ */ G$1(defaultPublicContext);
  function getInitialState() {
    return {
      draggable: {
        active: null,
        initialCoordinates: {
          x: 0,
          y: 0
        },
        nodes: /* @__PURE__ */ new Map(),
        translate: {
          x: 0,
          y: 0
        }
      },
      droppable: {
        containers: new DroppableContainersMap()
      }
    };
  }
  function reducer(state, action) {
    switch (action.type) {
      case Action.DragStart:
        return {
          ...state,
          draggable: {
            ...state.draggable,
            initialCoordinates: action.initialCoordinates,
            active: action.active
          }
        };
      case Action.DragMove:
        if (!state.draggable.active) {
          return state;
        }
        return {
          ...state,
          draggable: {
            ...state.draggable,
            translate: {
              x: action.coordinates.x - state.draggable.initialCoordinates.x,
              y: action.coordinates.y - state.draggable.initialCoordinates.y
            }
          }
        };
      case Action.DragEnd:
      case Action.DragCancel:
        return {
          ...state,
          draggable: {
            ...state.draggable,
            active: null,
            initialCoordinates: {
              x: 0,
              y: 0
            },
            translate: {
              x: 0,
              y: 0
            }
          }
        };
      case Action.RegisterDroppable: {
        const {
          element
        } = action;
        const {
          id
        } = element;
        const containers = new DroppableContainersMap(state.droppable.containers);
        containers.set(id, element);
        return {
          ...state,
          droppable: {
            ...state.droppable,
            containers
          }
        };
      }
      case Action.SetDroppableDisabled: {
        const {
          id,
          key,
          disabled
        } = action;
        const element = state.droppable.containers.get(id);
        if (!element || key !== element.key) {
          return state;
        }
        const containers = new DroppableContainersMap(state.droppable.containers);
        containers.set(id, {
          ...element,
          disabled
        });
        return {
          ...state,
          droppable: {
            ...state.droppable,
            containers
          }
        };
      }
      case Action.UnregisterDroppable: {
        const {
          id,
          key
        } = action;
        const element = state.droppable.containers.get(id);
        if (!element || key !== element.key) {
          return state;
        }
        const containers = new DroppableContainersMap(state.droppable.containers);
        containers.delete(id);
        return {
          ...state,
          droppable: {
            ...state.droppable,
            containers
          }
        };
      }
      default: {
        return state;
      }
    }
  }
  function RestoreFocus(_ref) {
    let {
      disabled
    } = _ref;
    const {
      active,
      activatorEvent,
      draggableNodes
    } = q$1(InternalContext);
    const previousActivatorEvent = usePrevious(activatorEvent);
    const previousActiveId = usePrevious(active == null ? void 0 : active.id);
    p(() => {
      if (disabled) {
        return;
      }
      if (!activatorEvent && previousActivatorEvent && previousActiveId != null) {
        if (!isKeyboardEvent(previousActivatorEvent)) {
          return;
        }
        if (document.activeElement === previousActivatorEvent.target) {
          return;
        }
        const draggableNode = draggableNodes.get(previousActiveId);
        if (!draggableNode) {
          return;
        }
        const {
          activatorNode,
          node
        } = draggableNode;
        if (!activatorNode.current && !node.current) {
          return;
        }
        requestAnimationFrame(() => {
          for (const element of [activatorNode.current, node.current]) {
            if (!element) {
              continue;
            }
            const focusableNode = findFirstFocusableNode(element);
            if (focusableNode) {
              focusableNode.focus();
              break;
            }
          }
        });
      }
    }, [activatorEvent, disabled, draggableNodes, previousActiveId, previousActivatorEvent]);
    return null;
  }
  function applyModifiers(modifiers, _ref) {
    let {
      transform,
      ...args
    } = _ref;
    return modifiers != null && modifiers.length ? modifiers.reduce((accumulator, modifier) => {
      return modifier({
        transform: accumulator,
        ...args
      });
    }, transform) : transform;
  }
  function useMeasuringConfiguration(config) {
    return F$1(
      () => ({
        draggable: {
          ...defaultMeasuringConfiguration.draggable,
          ...config == null ? void 0 : config.draggable
        },
        droppable: {
          ...defaultMeasuringConfiguration.droppable,
          ...config == null ? void 0 : config.droppable
        },
        dragOverlay: {
          ...defaultMeasuringConfiguration.dragOverlay,
          ...config == null ? void 0 : config.dragOverlay
        }
      }),
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [config == null ? void 0 : config.draggable, config == null ? void 0 : config.droppable, config == null ? void 0 : config.dragOverlay]
    );
  }
  function useLayoutShiftScrollCompensation(_ref) {
    let {
      activeNode,
      measure,
      initialRect,
      config = true
    } = _ref;
    const initialized = _$2(false);
    const {
      x: x2,
      y: y2
    } = typeof config === "boolean" ? {
      x: config,
      y: config
    } : config;
    useIsomorphicLayoutEffect(() => {
      const disabled = !x2 && !y2;
      if (disabled || !activeNode) {
        initialized.current = false;
        return;
      }
      if (initialized.current || !initialRect) {
        return;
      }
      const node = activeNode == null ? void 0 : activeNode.node.current;
      if (!node || node.isConnected === false) {
        return;
      }
      const rect = measure(node);
      const rectDelta = getRectDelta(rect, initialRect);
      if (!x2) {
        rectDelta.x = 0;
      }
      if (!y2) {
        rectDelta.y = 0;
      }
      initialized.current = true;
      if (Math.abs(rectDelta.x) > 0 || Math.abs(rectDelta.y) > 0) {
        const firstScrollableAncestor = getFirstScrollableAncestor(node);
        if (firstScrollableAncestor) {
          firstScrollableAncestor.scrollBy({
            top: rectDelta.y,
            left: rectDelta.x
          });
        }
      }
    }, [activeNode, x2, y2, initialRect, measure]);
  }
  const ActiveDraggableContext = /* @__PURE__ */ G$1({
    ...defaultCoordinates,
    scaleX: 1,
    scaleY: 1
  });
  var Status;
  (function(Status2) {
    Status2[Status2["Uninitialized"] = 0] = "Uninitialized";
    Status2[Status2["Initializing"] = 1] = "Initializing";
    Status2[Status2["Initialized"] = 2] = "Initialized";
  })(Status || (Status = {}));
  const DndContext = /* @__PURE__ */ x(function DndContext2(_ref) {
    var _sensorContext$curren, _dragOverlay$nodeRef$, _dragOverlay$rect, _over$rect;
    let {
      id,
      accessibility,
      autoScroll = true,
      children,
      sensors = defaultSensors,
      collisionDetection = rectIntersection,
      measuring,
      modifiers,
      ...props
    } = _ref;
    const store = s(reducer, void 0, getInitialState);
    const [state, dispatch] = store;
    const [dispatchMonitorEvent, registerMonitorListener] = useDndMonitorProvider();
    const [status, setStatus] = h(Status.Uninitialized);
    const isInitialized = status === Status.Initialized;
    const {
      draggable: {
        active: activeId,
        nodes: draggableNodes,
        translate
      },
      droppable: {
        containers: droppableContainers
      }
    } = state;
    const node = activeId ? draggableNodes.get(activeId) : null;
    const activeRects = _$2({
      initial: null,
      translated: null
    });
    const active = F$1(() => {
      var _node$data;
      return activeId != null ? {
        id: activeId,
        // It's possible for the active node to unmount while dragging
        data: (_node$data = node == null ? void 0 : node.data) != null ? _node$data : defaultData,
        rect: activeRects
      } : null;
    }, [activeId, node]);
    const activeRef = _$2(null);
    const [activeSensor, setActiveSensor] = h(null);
    const [activatorEvent, setActivatorEvent] = h(null);
    const latestProps = useLatestValue(props, Object.values(props));
    const draggableDescribedById = useUniqueId("DndDescribedBy", id);
    const enabledDroppableContainers = F$1(() => droppableContainers.getEnabled(), [droppableContainers]);
    const measuringConfiguration = useMeasuringConfiguration(measuring);
    const {
      droppableRects,
      measureDroppableContainers,
      measuringScheduled
    } = useDroppableMeasuring(enabledDroppableContainers, {
      dragging: isInitialized,
      dependencies: [translate.x, translate.y],
      config: measuringConfiguration.droppable
    });
    const activeNode = useCachedNode(draggableNodes, activeId);
    const activationCoordinates = F$1(() => activatorEvent ? getEventCoordinates(activatorEvent) : null, [activatorEvent]);
    const autoScrollOptions = getAutoScrollerOptions();
    const initialActiveNodeRect = useInitialRect(activeNode, measuringConfiguration.draggable.measure);
    useLayoutShiftScrollCompensation({
      activeNode: activeId ? draggableNodes.get(activeId) : null,
      config: autoScrollOptions.layoutShiftCompensation,
      initialRect: initialActiveNodeRect,
      measure: measuringConfiguration.draggable.measure
    });
    const activeNodeRect = useRect(activeNode, measuringConfiguration.draggable.measure, initialActiveNodeRect);
    const containerNodeRect = useRect(activeNode ? activeNode.parentElement : null);
    const sensorContext = _$2({
      activatorEvent: null,
      active: null,
      activeNode,
      collisionRect: null,
      collisions: null,
      droppableRects,
      draggableNodes,
      draggingNode: null,
      draggingNodeRect: null,
      droppableContainers,
      over: null,
      scrollableAncestors: [],
      scrollAdjustedTranslate: null
    });
    const overNode = droppableContainers.getNodeFor((_sensorContext$curren = sensorContext.current.over) == null ? void 0 : _sensorContext$curren.id);
    const dragOverlay = useDragOverlayMeasuring({
      measure: measuringConfiguration.dragOverlay.measure
    });
    const draggingNode = (_dragOverlay$nodeRef$ = dragOverlay.nodeRef.current) != null ? _dragOverlay$nodeRef$ : activeNode;
    const draggingNodeRect = isInitialized ? (_dragOverlay$rect = dragOverlay.rect) != null ? _dragOverlay$rect : activeNodeRect : null;
    const usesDragOverlay = Boolean(dragOverlay.nodeRef.current && dragOverlay.rect);
    const nodeRectDelta = useRectDelta(usesDragOverlay ? null : activeNodeRect);
    const windowRect = useWindowRect(draggingNode ? getWindow(draggingNode) : null);
    const scrollableAncestors = useScrollableAncestors(isInitialized ? overNode != null ? overNode : activeNode : null);
    const scrollableAncestorRects = useRects(scrollableAncestors);
    const modifiedTranslate = applyModifiers(modifiers, {
      transform: {
        x: translate.x - nodeRectDelta.x,
        y: translate.y - nodeRectDelta.y,
        scaleX: 1,
        scaleY: 1
      },
      activatorEvent,
      active,
      activeNodeRect,
      containerNodeRect,
      draggingNodeRect,
      over: sensorContext.current.over,
      overlayNodeRect: dragOverlay.rect,
      scrollableAncestors,
      scrollableAncestorRects,
      windowRect
    });
    const pointerCoordinates = activationCoordinates ? add(activationCoordinates, translate) : null;
    const scrollOffsets = useScrollOffsets(scrollableAncestors);
    const scrollAdjustment = useScrollOffsetsDelta(scrollOffsets);
    const activeNodeScrollDelta = useScrollOffsetsDelta(scrollOffsets, [activeNodeRect]);
    const scrollAdjustedTranslate = add(modifiedTranslate, scrollAdjustment);
    const collisionRect = draggingNodeRect ? getAdjustedRect(draggingNodeRect, modifiedTranslate) : null;
    const collisions = active && collisionRect ? collisionDetection({
      active,
      collisionRect,
      droppableRects,
      droppableContainers: enabledDroppableContainers,
      pointerCoordinates
    }) : null;
    const overId = getFirstCollision(collisions, "id");
    const [over, setOver] = h(null);
    const appliedTranslate = usesDragOverlay ? modifiedTranslate : add(modifiedTranslate, activeNodeScrollDelta);
    const transform = adjustScale(appliedTranslate, (_over$rect = over == null ? void 0 : over.rect) != null ? _over$rect : null, activeNodeRect);
    const instantiateSensor = T$1(
      (event, _ref2) => {
        let {
          sensor: Sensor,
          options
        } = _ref2;
        if (activeRef.current == null) {
          return;
        }
        const activeNode2 = draggableNodes.get(activeRef.current);
        if (!activeNode2) {
          return;
        }
        const activatorEvent2 = event.nativeEvent;
        const sensorInstance = new Sensor({
          active: activeRef.current,
          activeNode: activeNode2,
          event: activatorEvent2,
          options,
          // Sensors need to be instantiated with refs for arguments that change over time
          // otherwise they are frozen in time with the stale arguments
          context: sensorContext,
          onStart(initialCoordinates) {
            const id2 = activeRef.current;
            if (id2 == null) {
              return;
            }
            const draggableNode = draggableNodes.get(id2);
            if (!draggableNode) {
              return;
            }
            const {
              onDragStart
            } = latestProps.current;
            const event2 = {
              active: {
                id: id2,
                data: draggableNode.data,
                rect: activeRects
              }
            };
            dn(() => {
              onDragStart == null ? void 0 : onDragStart(event2);
              setStatus(Status.Initializing);
              dispatch({
                type: Action.DragStart,
                initialCoordinates,
                active: id2
              });
              dispatchMonitorEvent({
                type: "onDragStart",
                event: event2
              });
            });
          },
          onMove(coordinates) {
            dispatch({
              type: Action.DragMove,
              coordinates
            });
          },
          onEnd: createHandler(Action.DragEnd),
          onCancel: createHandler(Action.DragCancel)
        });
        dn(() => {
          setActiveSensor(sensorInstance);
          setActivatorEvent(event.nativeEvent);
        });
        function createHandler(type) {
          return async function handler() {
            const {
              active: active2,
              collisions: collisions2,
              over: over2,
              scrollAdjustedTranslate: scrollAdjustedTranslate2
            } = sensorContext.current;
            let event2 = null;
            if (active2 && scrollAdjustedTranslate2) {
              const {
                cancelDrop
              } = latestProps.current;
              event2 = {
                activatorEvent: activatorEvent2,
                active: active2,
                collisions: collisions2,
                delta: scrollAdjustedTranslate2,
                over: over2
              };
              if (type === Action.DragEnd && typeof cancelDrop === "function") {
                const shouldCancel = await Promise.resolve(cancelDrop(event2));
                if (shouldCancel) {
                  type = Action.DragCancel;
                }
              }
            }
            activeRef.current = null;
            dn(() => {
              dispatch({
                type
              });
              setStatus(Status.Uninitialized);
              setOver(null);
              setActiveSensor(null);
              setActivatorEvent(null);
              const eventName = type === Action.DragEnd ? "onDragEnd" : "onDragCancel";
              if (event2) {
                const handler2 = latestProps.current[eventName];
                handler2 == null ? void 0 : handler2(event2);
                dispatchMonitorEvent({
                  type: eventName,
                  event: event2
                });
              }
            });
          };
        }
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [draggableNodes]
    );
    const bindActivatorToSensorInstantiator = T$1((handler, sensor) => {
      return (event, active2) => {
        const nativeEvent = event.nativeEvent;
        const activeDraggableNode = draggableNodes.get(active2);
        if (
          // Another sensor is already instantiating
          activeRef.current !== null || // No active draggable
          !activeDraggableNode || // Event has already been captured
          nativeEvent.dndKit || nativeEvent.defaultPrevented
        ) {
          return;
        }
        const activationContext = {
          active: activeDraggableNode
        };
        const shouldActivate = handler(event, sensor.options, activationContext);
        if (shouldActivate === true) {
          nativeEvent.dndKit = {
            capturedBy: sensor.sensor
          };
          activeRef.current = active2;
          instantiateSensor(event, sensor);
        }
      };
    }, [draggableNodes, instantiateSensor]);
    const activators = useCombineActivators(sensors, bindActivatorToSensorInstantiator);
    useSensorSetup(sensors);
    useIsomorphicLayoutEffect(() => {
      if (activeNodeRect && status === Status.Initializing) {
        setStatus(Status.Initialized);
      }
    }, [activeNodeRect, status]);
    p(
      () => {
        const {
          onDragMove
        } = latestProps.current;
        const {
          active: active2,
          activatorEvent: activatorEvent2,
          collisions: collisions2,
          over: over2
        } = sensorContext.current;
        if (!active2 || !activatorEvent2) {
          return;
        }
        const event = {
          active: active2,
          activatorEvent: activatorEvent2,
          collisions: collisions2,
          delta: {
            x: scrollAdjustedTranslate.x,
            y: scrollAdjustedTranslate.y
          },
          over: over2
        };
        dn(() => {
          onDragMove == null ? void 0 : onDragMove(event);
          dispatchMonitorEvent({
            type: "onDragMove",
            event
          });
        });
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [scrollAdjustedTranslate.x, scrollAdjustedTranslate.y]
    );
    p(
      () => {
        const {
          active: active2,
          activatorEvent: activatorEvent2,
          collisions: collisions2,
          droppableContainers: droppableContainers2,
          scrollAdjustedTranslate: scrollAdjustedTranslate2
        } = sensorContext.current;
        if (!active2 || activeRef.current == null || !activatorEvent2 || !scrollAdjustedTranslate2) {
          return;
        }
        const {
          onDragOver
        } = latestProps.current;
        const overContainer = droppableContainers2.get(overId);
        const over2 = overContainer && overContainer.rect.current ? {
          id: overContainer.id,
          rect: overContainer.rect.current,
          data: overContainer.data,
          disabled: overContainer.disabled
        } : null;
        const event = {
          active: active2,
          activatorEvent: activatorEvent2,
          collisions: collisions2,
          delta: {
            x: scrollAdjustedTranslate2.x,
            y: scrollAdjustedTranslate2.y
          },
          over: over2
        };
        dn(() => {
          setOver(over2);
          onDragOver == null ? void 0 : onDragOver(event);
          dispatchMonitorEvent({
            type: "onDragOver",
            event
          });
        });
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [overId]
    );
    useIsomorphicLayoutEffect(() => {
      sensorContext.current = {
        activatorEvent,
        active,
        activeNode,
        collisionRect,
        collisions,
        droppableRects,
        draggableNodes,
        draggingNode,
        draggingNodeRect,
        droppableContainers,
        over,
        scrollableAncestors,
        scrollAdjustedTranslate
      };
      activeRects.current = {
        initial: draggingNodeRect,
        translated: collisionRect
      };
    }, [active, activeNode, collisions, collisionRect, draggableNodes, draggingNode, draggingNodeRect, droppableRects, droppableContainers, over, scrollableAncestors, scrollAdjustedTranslate]);
    useAutoScroller({
      ...autoScrollOptions,
      delta: translate,
      draggingRect: collisionRect,
      pointerCoordinates,
      scrollableAncestors,
      scrollableAncestorRects
    });
    const publicContext = F$1(() => {
      const context = {
        active,
        activeNode,
        activeNodeRect,
        activatorEvent,
        collisions,
        containerNodeRect,
        dragOverlay,
        draggableNodes,
        droppableContainers,
        droppableRects,
        over,
        measureDroppableContainers,
        scrollableAncestors,
        scrollableAncestorRects,
        measuringConfiguration,
        measuringScheduled,
        windowRect
      };
      return context;
    }, [active, activeNode, activeNodeRect, activatorEvent, collisions, containerNodeRect, dragOverlay, draggableNodes, droppableContainers, droppableRects, over, measureDroppableContainers, scrollableAncestors, scrollableAncestorRects, measuringConfiguration, measuringScheduled, windowRect]);
    const internalContext = F$1(() => {
      const context = {
        activatorEvent,
        activators,
        active,
        activeNodeRect,
        ariaDescribedById: {
          draggable: draggableDescribedById
        },
        dispatch,
        draggableNodes,
        over,
        measureDroppableContainers
      };
      return context;
    }, [activatorEvent, activators, active, activeNodeRect, dispatch, draggableDescribedById, draggableNodes, over, measureDroppableContainers]);
    return Cn.createElement(DndMonitorContext.Provider, {
      value: registerMonitorListener
    }, Cn.createElement(InternalContext.Provider, {
      value: internalContext
    }, Cn.createElement(PublicContext.Provider, {
      value: publicContext
    }, Cn.createElement(ActiveDraggableContext.Provider, {
      value: transform
    }, children)), Cn.createElement(RestoreFocus, {
      disabled: (accessibility == null ? void 0 : accessibility.restoreFocus) === false
    })), Cn.createElement(Accessibility, {
      ...accessibility,
      hiddenTextDescribedById: draggableDescribedById
    }));
    function getAutoScrollerOptions() {
      const activeSensorDisablesAutoscroll = (activeSensor == null ? void 0 : activeSensor.autoScrollEnabled) === false;
      const autoScrollGloballyDisabled = typeof autoScroll === "object" ? autoScroll.enabled === false : autoScroll === false;
      const enabled = isInitialized && !activeSensorDisablesAutoscroll && !autoScrollGloballyDisabled;
      if (typeof autoScroll === "object") {
        return {
          ...autoScroll,
          enabled
        };
      }
      return {
        enabled
      };
    }
  });
  const NullContext = /* @__PURE__ */ G$1(null);
  const defaultRole = "button";
  const ID_PREFIX$1 = "Droppable";
  function useDraggable(_ref) {
    let {
      id,
      data,
      disabled = false,
      attributes
    } = _ref;
    const key = useUniqueId(ID_PREFIX$1);
    const {
      activators,
      activatorEvent,
      active,
      activeNodeRect,
      ariaDescribedById,
      draggableNodes,
      over
    } = q$1(InternalContext);
    const {
      role = defaultRole,
      roleDescription = "draggable",
      tabIndex = 0
    } = attributes != null ? attributes : {};
    const isDragging = (active == null ? void 0 : active.id) === id;
    const transform = q$1(isDragging ? ActiveDraggableContext : NullContext);
    const [node, setNodeRef] = useNodeRef();
    const [activatorNode, setActivatorNodeRef] = useNodeRef();
    const listeners = useSyntheticListeners(activators, id);
    const dataRef = useLatestValue(data);
    useIsomorphicLayoutEffect(
      () => {
        draggableNodes.set(id, {
          id,
          key,
          node,
          activatorNode,
          data: dataRef
        });
        return () => {
          const node2 = draggableNodes.get(id);
          if (node2 && node2.key === key) {
            draggableNodes.delete(id);
          }
        };
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [draggableNodes, id]
    );
    const memoizedAttributes = F$1(() => ({
      role,
      tabIndex,
      "aria-disabled": disabled,
      "aria-pressed": isDragging && role === defaultRole ? true : void 0,
      "aria-roledescription": roleDescription,
      "aria-describedby": ariaDescribedById.draggable
    }), [disabled, role, tabIndex, isDragging, roleDescription, ariaDescribedById.draggable]);
    return {
      active,
      activatorEvent,
      activeNodeRect,
      attributes: memoizedAttributes,
      isDragging,
      listeners: disabled ? void 0 : listeners,
      node,
      over,
      setNodeRef,
      setActivatorNodeRef,
      transform
    };
  }
  function useDndContext() {
    return q$1(PublicContext);
  }
  const ID_PREFIX$1$1 = "Droppable";
  const defaultResizeObserverConfig = {
    timeout: 25
  };
  function useDroppable(_ref) {
    let {
      data,
      disabled = false,
      id,
      resizeObserverConfig
    } = _ref;
    const key = useUniqueId(ID_PREFIX$1$1);
    const {
      active,
      dispatch,
      over,
      measureDroppableContainers
    } = q$1(InternalContext);
    const previous = _$2({
      disabled
    });
    const resizeObserverConnected = _$2(false);
    const rect = _$2(null);
    const callbackId = _$2(null);
    const {
      disabled: resizeObserverDisabled,
      updateMeasurementsFor,
      timeout: resizeObserverTimeout
    } = {
      ...defaultResizeObserverConfig,
      ...resizeObserverConfig
    };
    const ids2 = useLatestValue(updateMeasurementsFor != null ? updateMeasurementsFor : id);
    const handleResize = T$1(
      () => {
        if (!resizeObserverConnected.current) {
          resizeObserverConnected.current = true;
          return;
        }
        if (callbackId.current != null) {
          clearTimeout(callbackId.current);
        }
        callbackId.current = setTimeout(() => {
          measureDroppableContainers(Array.isArray(ids2.current) ? ids2.current : [ids2.current]);
          callbackId.current = null;
        }, resizeObserverTimeout);
      },
      //eslint-disable-next-line react-hooks/exhaustive-deps
      [resizeObserverTimeout]
    );
    const resizeObserver = useResizeObserver({
      callback: handleResize,
      disabled: resizeObserverDisabled || !active
    });
    const handleNodeChange = T$1((newElement, previousElement) => {
      if (!resizeObserver) {
        return;
      }
      if (previousElement) {
        resizeObserver.unobserve(previousElement);
        resizeObserverConnected.current = false;
      }
      if (newElement) {
        resizeObserver.observe(newElement);
      }
    }, [resizeObserver]);
    const [nodeRef, setNodeRef] = useNodeRef(handleNodeChange);
    const dataRef = useLatestValue(data);
    p(() => {
      if (!resizeObserver || !nodeRef.current) {
        return;
      }
      resizeObserver.disconnect();
      resizeObserverConnected.current = false;
      resizeObserver.observe(nodeRef.current);
    }, [nodeRef, resizeObserver]);
    useIsomorphicLayoutEffect(
      () => {
        dispatch({
          type: Action.RegisterDroppable,
          element: {
            id,
            key,
            disabled,
            node: nodeRef,
            rect,
            data: dataRef
          }
        });
        return () => dispatch({
          type: Action.UnregisterDroppable,
          key,
          id
        });
      },
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [id]
    );
    p(() => {
      if (disabled !== previous.current.disabled) {
        dispatch({
          type: Action.SetDroppableDisabled,
          id,
          key,
          disabled
        });
        previous.current.disabled = disabled;
      }
    }, [id, key, disabled, dispatch]);
    return {
      active,
      rect,
      isOver: (over == null ? void 0 : over.id) === id,
      node: nodeRef,
      over,
      setNodeRef
    };
  }
  function arrayMove(array, from, to) {
    const newArray = array.slice();
    newArray.splice(to < 0 ? newArray.length + to : to, 0, newArray.splice(from, 1)[0]);
    return newArray;
  }
  function getSortedRects(items, rects) {
    return items.reduce((accumulator, id, index2) => {
      const rect = rects.get(id);
      if (rect) {
        accumulator[index2] = rect;
      }
      return accumulator;
    }, Array(items.length));
  }
  function isValidIndex(index2) {
    return index2 !== null && index2 >= 0;
  }
  function itemsEqual(a2, b2) {
    if (a2 === b2) {
      return true;
    }
    if (a2.length !== b2.length) {
      return false;
    }
    for (let i2 = 0; i2 < a2.length; i2++) {
      if (a2[i2] !== b2[i2]) {
        return false;
      }
    }
    return true;
  }
  function normalizeDisabled(disabled) {
    if (typeof disabled === "boolean") {
      return {
        draggable: disabled,
        droppable: disabled
      };
    }
    return disabled;
  }
  const rectSortingStrategy = (_ref) => {
    let {
      rects,
      activeIndex,
      overIndex,
      index: index2
    } = _ref;
    const newRects = arrayMove(rects, overIndex, activeIndex);
    const oldRect = rects[index2];
    const newRect = newRects[index2];
    if (!newRect || !oldRect) {
      return null;
    }
    return {
      x: newRect.left - oldRect.left,
      y: newRect.top - oldRect.top,
      scaleX: newRect.width / oldRect.width,
      scaleY: newRect.height / oldRect.height
    };
  };
  const defaultScale$1 = {
    scaleX: 1,
    scaleY: 1
  };
  const verticalListSortingStrategy = (_ref) => {
    var _rects$activeIndex;
    let {
      activeIndex,
      activeNodeRect: fallbackActiveRect,
      index: index2,
      rects,
      overIndex
    } = _ref;
    const activeNodeRect = (_rects$activeIndex = rects[activeIndex]) != null ? _rects$activeIndex : fallbackActiveRect;
    if (!activeNodeRect) {
      return null;
    }
    if (index2 === activeIndex) {
      const overIndexRect = rects[overIndex];
      if (!overIndexRect) {
        return null;
      }
      return {
        x: 0,
        y: activeIndex < overIndex ? overIndexRect.top + overIndexRect.height - (activeNodeRect.top + activeNodeRect.height) : overIndexRect.top - activeNodeRect.top,
        ...defaultScale$1
      };
    }
    const itemGap = getItemGap$1(rects, index2, activeIndex);
    if (index2 > activeIndex && index2 <= overIndex) {
      return {
        x: 0,
        y: -activeNodeRect.height - itemGap,
        ...defaultScale$1
      };
    }
    if (index2 < activeIndex && index2 >= overIndex) {
      return {
        x: 0,
        y: activeNodeRect.height + itemGap,
        ...defaultScale$1
      };
    }
    return {
      x: 0,
      y: 0,
      ...defaultScale$1
    };
  };
  function getItemGap$1(clientRects, index2, activeIndex) {
    const currentRect = clientRects[index2];
    const previousRect = clientRects[index2 - 1];
    const nextRect = clientRects[index2 + 1];
    if (!currentRect) {
      return 0;
    }
    if (activeIndex < index2) {
      return previousRect ? currentRect.top - (previousRect.top + previousRect.height) : nextRect ? nextRect.top - (currentRect.top + currentRect.height) : 0;
    }
    return nextRect ? nextRect.top - (currentRect.top + currentRect.height) : previousRect ? currentRect.top - (previousRect.top + previousRect.height) : 0;
  }
  const ID_PREFIX = "Sortable";
  const Context = /* @__PURE__ */ Cn.createContext({
    activeIndex: -1,
    containerId: ID_PREFIX,
    disableTransforms: false,
    items: [],
    overIndex: -1,
    useDragOverlay: false,
    sortedRects: [],
    strategy: rectSortingStrategy,
    disabled: {
      draggable: false,
      droppable: false
    }
  });
  function SortableContext(_ref) {
    let {
      children,
      id,
      items: userDefinedItems,
      strategy = rectSortingStrategy,
      disabled: disabledProp = false
    } = _ref;
    const {
      active,
      dragOverlay,
      droppableRects,
      over,
      measureDroppableContainers
    } = useDndContext();
    const containerId = useUniqueId(ID_PREFIX, id);
    const useDragOverlay = Boolean(dragOverlay.rect !== null);
    const items = F$1(() => userDefinedItems.map((item) => typeof item === "object" && "id" in item ? item.id : item), [userDefinedItems]);
    const isDragging = active != null;
    const activeIndex = active ? items.indexOf(active.id) : -1;
    const overIndex = over ? items.indexOf(over.id) : -1;
    const previousItemsRef = _$2(items);
    const itemsHaveChanged = !itemsEqual(items, previousItemsRef.current);
    const disableTransforms = overIndex !== -1 && activeIndex === -1 || itemsHaveChanged;
    const disabled = normalizeDisabled(disabledProp);
    useIsomorphicLayoutEffect(() => {
      if (itemsHaveChanged && isDragging) {
        measureDroppableContainers(items);
      }
    }, [itemsHaveChanged, items, isDragging, measureDroppableContainers]);
    p(() => {
      previousItemsRef.current = items;
    }, [items]);
    const contextValue = F$1(
      () => ({
        activeIndex,
        containerId,
        disabled,
        disableTransforms,
        items,
        overIndex,
        useDragOverlay,
        sortedRects: getSortedRects(items, droppableRects),
        strategy
      }),
      // eslint-disable-next-line react-hooks/exhaustive-deps
      [activeIndex, containerId, disabled.draggable, disabled.droppable, disableTransforms, items, overIndex, droppableRects, useDragOverlay, strategy]
    );
    return Cn.createElement(Context.Provider, {
      value: contextValue
    }, children);
  }
  const defaultNewIndexGetter = (_ref) => {
    let {
      id,
      items,
      activeIndex,
      overIndex
    } = _ref;
    return arrayMove(items, activeIndex, overIndex).indexOf(id);
  };
  const defaultAnimateLayoutChanges = (_ref2) => {
    let {
      containerId,
      isSorting,
      wasDragging,
      index: index2,
      items,
      newIndex,
      previousItems,
      previousContainerId,
      transition
    } = _ref2;
    if (!transition || !wasDragging) {
      return false;
    }
    if (previousItems !== items && index2 === newIndex) {
      return false;
    }
    if (isSorting) {
      return true;
    }
    return newIndex !== index2 && containerId === previousContainerId;
  };
  const defaultTransition = {
    duration: 200,
    easing: "ease"
  };
  const transitionProperty = "transform";
  const disabledTransition = /* @__PURE__ */ CSS.Transition.toString({
    property: transitionProperty,
    duration: 0,
    easing: "linear"
  });
  const defaultAttributes = {
    roleDescription: "sortable"
  };
  function useDerivedTransform(_ref) {
    let {
      disabled,
      index: index2,
      node,
      rect
    } = _ref;
    const [derivedTransform, setDerivedtransform] = h(null);
    const previousIndex = _$2(index2);
    useIsomorphicLayoutEffect(() => {
      if (!disabled && index2 !== previousIndex.current && node.current) {
        const initial = rect.current;
        if (initial) {
          const current = getClientRect(node.current, {
            ignoreTransform: true
          });
          const delta = {
            x: initial.left - current.left,
            y: initial.top - current.top,
            scaleX: initial.width / current.width,
            scaleY: initial.height / current.height
          };
          if (delta.x || delta.y) {
            setDerivedtransform(delta);
          }
        }
      }
      if (index2 !== previousIndex.current) {
        previousIndex.current = index2;
      }
    }, [disabled, index2, node, rect]);
    p(() => {
      if (derivedTransform) {
        setDerivedtransform(null);
      }
    }, [derivedTransform]);
    return derivedTransform;
  }
  function useSortable(_ref) {
    let {
      animateLayoutChanges = defaultAnimateLayoutChanges,
      attributes: userDefinedAttributes,
      disabled: localDisabled,
      data: customData,
      getNewIndex = defaultNewIndexGetter,
      id,
      strategy: localStrategy,
      resizeObserverConfig,
      transition = defaultTransition
    } = _ref;
    const {
      items,
      containerId,
      activeIndex,
      disabled: globalDisabled,
      disableTransforms,
      sortedRects,
      overIndex,
      useDragOverlay,
      strategy: globalStrategy
    } = q$1(Context);
    const disabled = normalizeLocalDisabled(localDisabled, globalDisabled);
    const index2 = items.indexOf(id);
    const data = F$1(() => ({
      sortable: {
        containerId,
        index: index2,
        items
      },
      ...customData
    }), [containerId, customData, index2, items]);
    const itemsAfterCurrentSortable = F$1(() => items.slice(items.indexOf(id)), [items, id]);
    const {
      rect,
      node,
      isOver,
      setNodeRef: setDroppableNodeRef
    } = useDroppable({
      id,
      data,
      disabled: disabled.droppable,
      resizeObserverConfig: {
        updateMeasurementsFor: itemsAfterCurrentSortable,
        ...resizeObserverConfig
      }
    });
    const {
      active,
      activatorEvent,
      activeNodeRect,
      attributes,
      setNodeRef: setDraggableNodeRef,
      listeners,
      isDragging,
      over,
      setActivatorNodeRef,
      transform
    } = useDraggable({
      id,
      data,
      attributes: {
        ...defaultAttributes,
        ...userDefinedAttributes
      },
      disabled: disabled.draggable
    });
    const setNodeRef = useCombinedRefs(setDroppableNodeRef, setDraggableNodeRef);
    const isSorting = Boolean(active);
    const displaceItem = isSorting && !disableTransforms && isValidIndex(activeIndex) && isValidIndex(overIndex);
    const shouldDisplaceDragSource = !useDragOverlay && isDragging;
    const dragSourceDisplacement = shouldDisplaceDragSource && displaceItem ? transform : null;
    const strategy = localStrategy != null ? localStrategy : globalStrategy;
    const finalTransform = displaceItem ? dragSourceDisplacement != null ? dragSourceDisplacement : strategy({
      rects: sortedRects,
      activeNodeRect,
      activeIndex,
      overIndex,
      index: index2
    }) : null;
    const newIndex = isValidIndex(activeIndex) && isValidIndex(overIndex) ? getNewIndex({
      id,
      items,
      activeIndex,
      overIndex
    }) : index2;
    const activeId = active == null ? void 0 : active.id;
    const previous = _$2({
      activeId,
      items,
      newIndex,
      containerId
    });
    const itemsHaveChanged = items !== previous.current.items;
    const shouldAnimateLayoutChanges = animateLayoutChanges({
      active,
      containerId,
      isDragging,
      isSorting,
      id,
      index: index2,
      items,
      newIndex: previous.current.newIndex,
      previousItems: previous.current.items,
      previousContainerId: previous.current.containerId,
      transition,
      wasDragging: previous.current.activeId != null
    });
    const derivedTransform = useDerivedTransform({
      disabled: !shouldAnimateLayoutChanges,
      index: index2,
      node,
      rect
    });
    p(() => {
      if (isSorting && previous.current.newIndex !== newIndex) {
        previous.current.newIndex = newIndex;
      }
      if (containerId !== previous.current.containerId) {
        previous.current.containerId = containerId;
      }
      if (items !== previous.current.items) {
        previous.current.items = items;
      }
    }, [isSorting, newIndex, containerId, items]);
    p(() => {
      if (activeId === previous.current.activeId) {
        return;
      }
      if (activeId && !previous.current.activeId) {
        previous.current.activeId = activeId;
        return;
      }
      const timeoutId = setTimeout(() => {
        previous.current.activeId = activeId;
      }, 50);
      return () => clearTimeout(timeoutId);
    }, [activeId]);
    return {
      active,
      activeIndex,
      attributes,
      data,
      rect,
      index: index2,
      newIndex,
      items,
      isOver,
      isSorting,
      isDragging,
      listeners,
      node,
      overIndex,
      over,
      setNodeRef,
      setActivatorNodeRef,
      setDroppableNodeRef,
      setDraggableNodeRef,
      transform: derivedTransform != null ? derivedTransform : finalTransform,
      transition: getTransition()
    };
    function getTransition() {
      if (
        // Temporarily disable transitions for a single frame to set up derived transforms
        derivedTransform || // Or to prevent items jumping to back to their "new" position when items change
        itemsHaveChanged && previous.current.newIndex === index2
      ) {
        return disabledTransition;
      }
      if (shouldDisplaceDragSource && !isKeyboardEvent(activatorEvent) || !transition) {
        return void 0;
      }
      if (isSorting || shouldAnimateLayoutChanges) {
        return CSS.Transition.toString({
          ...transition,
          property: transitionProperty
        });
      }
      return void 0;
    }
  }
  function normalizeLocalDisabled(localDisabled, globalDisabled) {
    var _localDisabled$dragga, _localDisabled$droppa;
    if (typeof localDisabled === "boolean") {
      return {
        draggable: localDisabled,
        // Backwards compatibility
        droppable: false
      };
    }
    return {
      draggable: (_localDisabled$dragga = localDisabled == null ? void 0 : localDisabled.draggable) != null ? _localDisabled$dragga : globalDisabled.draggable,
      droppable: (_localDisabled$droppa = localDisabled == null ? void 0 : localDisabled.droppable) != null ? _localDisabled$droppa : globalDisabled.droppable
    };
  }
  function hasSortableData(entry) {
    if (!entry) {
      return false;
    }
    const data = entry.data.current;
    if (data && "sortable" in data && typeof data.sortable === "object" && "containerId" in data.sortable && "items" in data.sortable && "index" in data.sortable) {
      return true;
    }
    return false;
  }
  const directions = [KeyboardCode.Down, KeyboardCode.Right, KeyboardCode.Up, KeyboardCode.Left];
  const sortableKeyboardCoordinates = (event, _ref) => {
    let {
      context: {
        active,
        collisionRect,
        droppableRects,
        droppableContainers,
        over,
        scrollableAncestors
      }
    } = _ref;
    if (directions.includes(event.code)) {
      event.preventDefault();
      if (!active || !collisionRect) {
        return;
      }
      const filteredContainers = [];
      droppableContainers.getEnabled().forEach((entry) => {
        if (!entry || entry != null && entry.disabled) {
          return;
        }
        const rect = droppableRects.get(entry.id);
        if (!rect) {
          return;
        }
        switch (event.code) {
          case KeyboardCode.Down:
            if (collisionRect.top < rect.top) {
              filteredContainers.push(entry);
            }
            break;
          case KeyboardCode.Up:
            if (collisionRect.top > rect.top) {
              filteredContainers.push(entry);
            }
            break;
          case KeyboardCode.Left:
            if (collisionRect.left > rect.left) {
              filteredContainers.push(entry);
            }
            break;
          case KeyboardCode.Right:
            if (collisionRect.left < rect.left) {
              filteredContainers.push(entry);
            }
            break;
        }
      });
      const collisions = closestCorners({
        active,
        collisionRect,
        droppableRects,
        droppableContainers: filteredContainers,
        pointerCoordinates: null
      });
      let closestId = getFirstCollision(collisions, "id");
      if (closestId === (over == null ? void 0 : over.id) && collisions.length > 1) {
        closestId = collisions[1].id;
      }
      if (closestId != null) {
        const activeDroppable = droppableContainers.get(active.id);
        const newDroppable = droppableContainers.get(closestId);
        const newRect = newDroppable ? droppableRects.get(newDroppable.id) : null;
        const newNode = newDroppable == null ? void 0 : newDroppable.node.current;
        if (newNode && newRect && activeDroppable && newDroppable) {
          const newScrollAncestors = getScrollableAncestors(newNode);
          const hasDifferentScrollAncestors = newScrollAncestors.some((element, index2) => scrollableAncestors[index2] !== element);
          const hasSameContainer = isSameContainer(activeDroppable, newDroppable);
          const isAfterActive = isAfter(activeDroppable, newDroppable);
          const offset = hasDifferentScrollAncestors || !hasSameContainer ? {
            x: 0,
            y: 0
          } : {
            x: isAfterActive ? collisionRect.width - newRect.width : 0,
            y: isAfterActive ? collisionRect.height - newRect.height : 0
          };
          const rectCoordinates = {
            x: newRect.left,
            y: newRect.top
          };
          const newCoordinates = offset.x && offset.y ? rectCoordinates : subtract(rectCoordinates, offset);
          return newCoordinates;
        }
      }
    }
    return void 0;
  };
  function isSameContainer(a2, b2) {
    if (!hasSortableData(a2) || !hasSortableData(b2)) {
      return false;
    }
    return a2.data.current.sortable.containerId === b2.data.current.sortable.containerId;
  }
  function isAfter(a2, b2) {
    if (!hasSortableData(a2) || !hasSortableData(b2)) {
      return false;
    }
    if (!isSameContainer(a2, b2)) {
      return false;
    }
    return a2.data.current.sortable.index < b2.data.current.sortable.index;
  }
  function restrictToBoundingRect(transform, rect, boundingRect) {
    const value = {
      ...transform
    };
    if (rect.top + transform.y <= boundingRect.top) {
      value.y = boundingRect.top - rect.top;
    } else if (rect.bottom + transform.y >= boundingRect.top + boundingRect.height) {
      value.y = boundingRect.top + boundingRect.height - rect.bottom;
    }
    if (rect.left + transform.x <= boundingRect.left) {
      value.x = boundingRect.left - rect.left;
    } else if (rect.right + transform.x >= boundingRect.left + boundingRect.width) {
      value.x = boundingRect.left + boundingRect.width - rect.right;
    }
    return value;
  }
  const restrictToVerticalAxis = (_ref) => {
    let {
      transform
    } = _ref;
    return {
      ...transform,
      x: 0
    };
  };
  const restrictToWindowEdges = (_ref) => {
    let {
      transform,
      draggingNodeRect,
      windowRect
    } = _ref;
    if (!draggingNodeRect || !windowRect) {
      return transform;
    }
    return restrictToBoundingRect(transform, draggingNodeRect, windowRect);
  };
  function dndHTMLAttributesTypeScriptCorrection(attributes) {
    return {
      ...attributes,
      role: attributes.role
    };
  }
  function getHandleDragEndFunction(setItems) {
    return (event) => {
      const {
        active,
        over
      } = event;
      if (active && over && active.id !== over.id) {
        const activeIdNumber = typeof active.id === "string" ? parseInt(active.id) : active.id;
        const overIdNumber = typeof over.id === "string" ? parseInt(over.id) : over.id;
        setItems((items) => {
          const oldIndex = items.map(({
            id
          }) => id).indexOf(activeIdNumber);
          const newIndex = items.map(({
            id
          }) => id).indexOf(overIdNumber);
          return arrayMove(items, oldIndex, newIndex);
        });
      }
    };
  }
  function SortableExercise(props) {
    const {
      attributes,
      listeners,
      setNodeRef,
      transform,
      transition
    } = useSortable({
      id: props.id
    });
    const style = {
      transform: CSS.Transform.toString(transform),
      transition
    };
    const alertContext = q$1(AlertContext);
    const sectionSelectionContext = q$1(SectionSelectionContext);
    function onClickDeleteExercise() {
      alertContext.setOptions({
        title: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueAlertDeleteExerciseTitle`),
        text: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueAlertDeleteExerciseText`, {
          exercise: props.customSelectionsExercises.exerciseTitle
        }),
        okButtonText: instance.t(`${LANG_NS_MAIN}:yes`),
        cancelButtonText: instance.t(`${LANG_NS_MAIN}:no`),
        okCallback: () => {
          sectionSelectionContext.deleteFromCustomSelectionsExercisesStorage({
            exerciseID: props.customSelectionsExercises.exerciseID
          });
        },
        cancelCallback: () => {
          return;
        }
      });
      alertContext.setOpen();
    }
    return o("li", {
      className: "SortableExercise",
      ref: setNodeRef,
      style,
      children: [o(DragHandleDots2Icon, {
        ...listeners,
        ...dndHTMLAttributesTypeScriptCorrection(attributes)
      }), o("span", {
        children: props.customSelectionsExercises.exerciseTitle
      }), o("button", {
        className: "SortableItemButton ButtonDelete",
        onClick: onClickDeleteExercise,
        children: o(CrossCircledIcon, {})
      }), o("div", {
        className: "FloatBarrier"
      }), o("div", {
        children: props.children
      })]
    });
  }
  function SortableSection(props) {
    const {
      attributes,
      listeners,
      setNodeRef,
      transform,
      transition
    } = useSortable({
      id: props.id
    });
    const style = {
      transform: CSS.Transform.toString(transform),
      transition
    };
    const alertContext = q$1(AlertContext);
    const sectionSelectionContext = q$1(SectionSelectionContext);
    function onClickDeleteSection() {
      alertContext.setOptions({
        title: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueAlertDeleteSectionTitle`),
        text: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueAlertDeleteSectionText`, {
          section: props.section.sectionTitle
        }),
        okButtonText: instance.t(`${LANG_NS_MAIN}:yes`),
        cancelButtonText: instance.t(`${LANG_NS_MAIN}:no`),
        okCallback: () => {
          sectionSelectionContext.deleteFromCustomSelectionSectionsStorage({
            hash: props.hash,
            sectionID: props.section.sectionID
          });
        },
        cancelCallback: () => {
          return;
        }
      });
      alertContext.setOpen();
    }
    return o("li", {
      className: "SortableSection",
      ref: setNodeRef,
      style,
      children: [o(DragHandleDots2Icon, {
        ...listeners,
        ...dndHTMLAttributesTypeScriptCorrection(attributes)
      }), o("span", {
        children: props.section.sectionTitle
      }), o("button", {
        className: "SortableItemButton ButtonDelete",
        onClick: onClickDeleteSection,
        children: o(CrossCircledIcon, {})
      }), o("div", {
        className: "FloatBarrier"
      })]
    });
  }
  const SortableSectionsCollection = (props) => {
    const sectionSelectionContext = q$1(SectionSelectionContext);
    const [itemsID] = h(props.sections.map(({
      sectionID
    }, index2) => {
      return {
        id: index2 + 1,
        sectionID
      };
    }));
    const [items, setItems] = h(props.sections.map((section, index2) => {
      return {
        id: index2 + 1,
        section
      };
    }));
    const sensors = useSensors(useSensor(PointerSensor), useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates
    }));
    function unchangedItemsIndicesFilter(selectionsStorage) {
      return ({
        section
      }, index2) => {
        var _a2;
        return section.index === ((_a2 = selectionsStorage[index2]) == null ? void 0 : _a2.index);
      };
    }
    p(() => {
      if (items.filter(unchangedItemsIndicesFilter(props.sections)).length === items.length) {
        return;
      }
      const customSectionsToModify = [];
      items.forEach(({
        section
      }, itemsIndex) => {
        if (section.index !== props.sections[itemsIndex].index) {
          const onModifiedIndexDeepCopy = JSON.parse(JSON.stringify(props.sections.filter((filterProps) => filterProps.index === section.index)[0]));
          onModifiedIndexDeepCopy.index = props.sections[itemsIndex].index;
          customSectionsToModify.push({
            ...onModifiedIndexDeepCopy,
            hash: props.hash
          });
        }
      });
      if (customSectionsToModify.length > 0) {
        sectionSelectionContext.setMultipleInCustomSelectionSectionsStorage(customSectionsToModify);
      }
    }, [items]);
    p(() => {
      setItems(props.sections.map((oneCustomSelectionSection, index2) => {
        const itemIdMatch = itemsID.filter(({
          sectionID
        }) => sectionID === oneCustomSelectionSection.sectionID);
        const itemId = itemIdMatch && itemIdMatch.length > 0 ? itemIdMatch[0].id : index2 + 1;
        return {
          id: itemId,
          section: oneCustomSelectionSection
        };
      }));
    }, [props.sections]);
    return o(DndContext, {
      modifiers: [restrictToVerticalAxis, restrictToWindowEdges],
      sensors,
      collisionDetection: closestCenter,
      onDragEnd: getHandleDragEndFunction(setItems),
      children: o("ul", {
        className: "SortableSectionsCollection",
        children: o(SortableContext, {
          items,
          strategy: verticalListSortingStrategy,
          children: items.map(({
            id,
            section
          }) => o(SortableSection, {
            id,
            section,
            hash: props.hash
          }, id))
        })
      })
    });
  };
  function SortableCustomSelection(props) {
    const {
      attributes,
      listeners,
      setNodeRef,
      transform,
      transition
    } = useSortable({
      id: props.id
    });
    const style = {
      transform: CSS.Transform.toString(transform),
      transition
    };
    const alertContext = q$1(AlertContext);
    const sectionSelectionContext = q$1(SectionSelectionContext);
    const settingsContext = q$1(SettingsContext);
    const firebaseContext = q$1(FirebaseContext);
    const [openSections, setOpenSections] = h(false);
    const [goToPageInitiated, setGoToPageInitiated] = h(false);
    p(() => {
      if (goToPageInitiated) {
        window.location.href = getExerciseURLFromSelectionContext(sectionSelectionContext);
      }
    }, [sectionSelectionContext.selectedSections]);
    const [lastPracticedString, setLastPracticedString] = h(instance.t(`${LANG_NS_MAIN}:lastPracticedNever`));
    const [practicesToday2, setPracticesToday] = h(0);
    const [practicesTotal2, setPracticesTotal] = h(0);
    p(() => {
      const curStatistics = getDefinedCustomSelectionStatistics(props.customSelectionStorage);
      if (settingsContext.options.enableFirebaseSync && props.customSelectionStorage.hash in firebaseContext.syncedStatistics) {
        const syncedStatistics = firebaseContext.syncedStatistics[props.customSelectionStorage.hash];
        if (!curStatistics.lastPracticed && syncedStatistics.lastPracticed || curStatistics.lastPracticed && syncedStatistics.lastPracticed && new Date(syncedStatistics.lastPracticed).getDate() > new Date(curStatistics.lastPracticed).getDate()) {
          curStatistics.lastPracticed = syncedStatistics.lastPracticed;
        }
        if (syncedStatistics.lastPracticed && isDateToday(new Date(syncedStatistics.lastPracticed))) {
          curStatistics.practicesToday += syncedStatistics.practicesToday;
        }
        curStatistics.practicesTotal += syncedStatistics.practicesTotal;
      }
      if (curStatistics.lastPracticed) {
        setLastPracticedString(new Date(curStatistics.lastPracticed).toLocaleString());
      }
      setPracticesToday(curStatistics.practicesToday);
      setPracticesTotal(curStatistics.practicesTotal);
    }, [props.customSelectionStorage.lastPracticed, props.customSelectionStorage.practicesToday, props.customSelectionStorage.practicesTotal, settingsContext.options.enableFirebaseSync, firebaseContext.syncedStatistics]);
    function onClickDeleteCustomSelection() {
      alertContext.setOptions({
        title: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueAlertDeleteCustomExerciseTitle`),
        text: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueAlertDeleteCustomExerciseText`, {
          exercise: props.customSelectionStorage.name
        }),
        okButtonText: instance.t(`${LANG_NS_MAIN}:yes`),
        cancelButtonText: instance.t(`${LANG_NS_MAIN}:no`),
        okCallback: () => {
          sectionSelectionContext.deleteFromCustomSelectionsStorage({
            hash: props.customSelectionStorage.hash
          });
        },
        cancelCallback: () => {
          return;
        }
      });
      alertContext.setOpen();
    }
    function onClickEditCustomSelection() {
      setGoToPageInitiated(true);
      sectionSelectionContext.setSelectedExercise({
        exerciseID: props.customSelectionStorage.exerciseID,
        exerciseTitle: getTitleFromExerciseID({
          exerciseID: props.customSelectionStorage.exerciseID,
          sectionSelectionContext
        })
      });
      sectionSelectionContext.setMultipleSelectedSections(props.customSelectionStorage.sections.map(sectionsMapperRestoreElementIDs(props.customSelectionStorage.exerciseID)));
    }
    return o("li", {
      className: "SortableCustomSelection",
      ref: setNodeRef,
      style,
      children: [o(DragHandleDots2Icon, {
        ...listeners,
        ...dndHTMLAttributesTypeScriptCorrection(attributes)
      }), o("span", {
        children: o("a", {
          className: "CustomSelectionLink",
          href: getPracticeSelectionURLFromSelectionContext({
            selectedExercise: {
              exerciseID: props.customSelectionStorage.exerciseID
            },
            selectedSections: props.customSelectionStorage.sections
          }),
          children: [o(ExternalLinkIcon, {}), " ", props.customSelectionStorage.name, " (", instance.t(`${LANG_NS_MAIN}:wordalistSection`, {
            count: props.customSelectionStorage.sections.length
          }), ")"]
        })
      }), o("div", {
        className: "CustomSelectionButtonGroup",
        children: [o("button", {
          className: "SortableItemButton ButtonDelete",
          onClick: onClickDeleteCustomSelection,
          children: o(CrossCircledIcon, {})
        }), o("button", {
          className: `SortableItemButton ButtonAction${openSections ? " ButtonActive" : ""}`,
          onClick: () => setOpenSections(!openSections),
          children: o(DropdownMenuIcon, {})
        }), o("button", {
          className: "SortableItemButton ButtonAction",
          onClick: onClickEditCustomSelection,
          children: o(Pencil2Icon, {})
        })]
      }), o("div", {
        className: "FloatBarrier"
      }), o("div", {
        className: "CustomSelectionStatistics",
        children: [o("span", {
          className: `SectionPracticesToday${practicesToday2 > 0 ? "" : " NotPracticedToday"}`,
          children: [instance.t(`${LANG_NS_MAIN}:practicesToday`), ": ", `${practicesToday2}`]
        }), o("span", {
          className: "SectionPracticesTotal",
          children: [instance.t(`${LANG_NS_MAIN}:practicesTotal`), ": ", practicesTotal2]
        }), o("span", {
          className: "SectionLastPractice",
          children: [instance.t(`${LANG_NS_MAIN}:lastPracticed`), ": ", lastPracticedString]
        }), o("div", {
          className: "FloatBarrier"
        })]
      }), o("div", {
        className: "FloatBarrier"
      }), openSections && o(SortableSectionsCollection, {
        sections: props.customSelectionStorage.sections,
        hash: props.customSelectionStorage.hash
      })]
    });
  }
  const SortableCustomSelectionsCollection = (props) => {
    const sectionSelectionContext = q$1(SectionSelectionContext);
    const [itemsID] = h(sectionSelectionContext.customSelectionsStorage.filter(propFilterExerciseID(props.exerciseID)).map((oneCustomSelectionStorage, index2) => {
      return {
        id: index2 + 1,
        hash: oneCustomSelectionStorage.hash
      };
    }));
    const [items, setItems] = h(sectionSelectionContext.customSelectionsStorage.filter(propFilterExerciseID(props.exerciseID)).map((oneCustomSelectionStorage, index2) => {
      return {
        id: index2 + 1,
        customSelectionStorage: oneCustomSelectionStorage
      };
    }));
    const sensors = useSensors(useSensor(PointerSensor), useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates
    }));
    function unchangedItemsIndicesFilter(selectionsStorage) {
      return ({
        customSelectionStorage
      }, index2) => {
        var _a2;
        return customSelectionStorage.index === ((_a2 = selectionsStorage[index2]) == null ? void 0 : _a2.index);
      };
    }
    p(() => {
      const filteredStorage = sectionSelectionContext.customSelectionsStorage.filter(propFilterExerciseID(props.exerciseID));
      if (items.filter(unchangedItemsIndicesFilter(filteredStorage)).length === items.length) {
        return;
      }
      const customSelectionsToModify = [];
      items.forEach(({
        customSelectionStorage
      }, itemsIndex) => {
        if (customSelectionStorage.index !== filteredStorage[itemsIndex].index) {
          const onModifiedIndexDeepCopy = JSON.parse(JSON.stringify(filteredStorage.filter((filterProps) => filterProps.index === customSelectionStorage.index)[0]));
          onModifiedIndexDeepCopy.index = filteredStorage[itemsIndex].index;
          customSelectionsToModify.push({
            ...onModifiedIndexDeepCopy,
            exerciseTitle: getTitleFromExerciseID({
              exerciseID: onModifiedIndexDeepCopy.exerciseID,
              sectionSelectionContext
            }),
            sections: onModifiedIndexDeepCopy.sections.map(sectionsMapperRestoreElementIDs(customSelectionStorage.exerciseID))
          });
        }
      });
      if (customSelectionsToModify.length > 0) {
        sectionSelectionContext.setMultipleInCustomSelectionsStorage({
          customSelectionsStorageSetters: customSelectionsToModify
        });
      }
    }, [items]);
    p(() => {
      setItems(sectionSelectionContext.customSelectionsStorage.filter(propFilterExerciseID(props.exerciseID)).map((oneCustomSelectionStorage, index2) => {
        const itemIdMatch = itemsID.filter(propFilterCustomSelectionHash(oneCustomSelectionStorage.hash));
        const itemId = itemIdMatch && itemIdMatch.length > 0 ? itemIdMatch[0].id : index2 + 1;
        return {
          id: itemId,
          customSelectionStorage: oneCustomSelectionStorage
        };
      }));
    }, [sectionSelectionContext.customSelectionsStorage]);
    return o(DndContext, {
      modifiers: [restrictToVerticalAxis, restrictToWindowEdges],
      sensors,
      collisionDetection: closestCenter,
      onDragEnd: getHandleDragEndFunction(setItems),
      children: o("ul", {
        className: "SortableCustomSelectionsCollection",
        children: o(SortableContext, {
          items,
          strategy: verticalListSortingStrategy,
          children: items.map(({
            id,
            customSelectionStorage
          }) => o(SortableCustomSelection, {
            id,
            customSelectionStorage
          }, id))
        })
      })
    });
  };
  const SortableExercisesCollection = () => {
    const sectionSelectionContext = q$1(SectionSelectionContext);
    const [itemsID] = h(sectionSelectionContext.customSelectionsExercisesStorage.map((oneCustomSelectionsExercise, index2) => {
      return {
        id: index2 + 1,
        exerciseID: oneCustomSelectionsExercise.exerciseID
      };
    }));
    const [items, setItems] = h(sectionSelectionContext.customSelectionsExercisesStorage.map((oneCustomSelectionsExercise, index2) => {
      return {
        id: index2 + 1,
        customSelectionsExercises: oneCustomSelectionsExercise
      };
    }));
    const sensors = useSensors(useSensor(PointerSensor), useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates
    }));
    function unchangedItemsIndicesFilter(selectionsStorage) {
      return ({
        customSelectionsExercises
      }, index2) => {
        var _a2;
        return customSelectionsExercises.index === ((_a2 = selectionsStorage[index2]) == null ? void 0 : _a2.index);
      };
    }
    p(() => {
      if (items.filter(unchangedItemsIndicesFilter(sectionSelectionContext.customSelectionsExercisesStorage)).length === items.length) {
        return;
      }
      const customSelectionsExercisesToModify = [];
      items.forEach(({
        customSelectionsExercises
      }, itemsIndex) => {
        if (customSelectionsExercises.index !== sectionSelectionContext.customSelectionsExercisesStorage[itemsIndex].index) {
          const onModifiedIndexDeepCopy = JSON.parse(JSON.stringify(sectionSelectionContext.customSelectionsExercisesStorage.filter((filterProps) => filterProps.index === customSelectionsExercises.index)[0]));
          onModifiedIndexDeepCopy.index = sectionSelectionContext.customSelectionsExercisesStorage[itemsIndex].index;
          customSelectionsExercisesToModify.push(onModifiedIndexDeepCopy);
        }
      });
      if (customSelectionsExercisesToModify.length > 0) {
        sectionSelectionContext.setMultipleInCustomSelectionsExercisesStorage({
          customSelectionsExercisesStorageSetters: customSelectionsExercisesToModify
        });
      }
    }, [items]);
    p(() => {
      setItems(sectionSelectionContext.customSelectionsExercisesStorage.map((oneCustomSelectionsExercise, index2) => {
        const itemIdMatch = itemsID.filter(propFilterExerciseID(oneCustomSelectionsExercise.exerciseID));
        const itemId = itemIdMatch ? itemIdMatch[0].id : index2 + 1;
        return {
          id: itemId,
          customSelectionsExercises: oneCustomSelectionsExercise
        };
      }));
    }, [sectionSelectionContext.customSelectionsExercisesStorage]);
    return o(DndContext, {
      modifiers: [restrictToVerticalAxis, restrictToWindowEdges],
      sensors,
      collisionDetection: closestCenter,
      onDragEnd: getHandleDragEndFunction(setItems),
      children: o("ul", {
        className: "SortableExercisesCollection",
        children: o(SortableContext, {
          items,
          strategy: verticalListSortingStrategy,
          children: items.map(({
            id,
            customSelectionsExercises
          }) => o(SortableExercise, {
            id,
            customSelectionsExercises,
            children: o(SortableCustomSelectionsCollection, {
              exerciseID: customSelectionsExercises.exerciseID
            })
          }, id))
        })
      })
    });
  };
  const CustomSelectionsStorageDialogue = () => {
    const notificationContext = q$1(NotificationContext);
    const sectionSelectionContext = q$1(SectionSelectionContext);
    const [currentView, setCurrentView] = h(null);
    const textareaImportElement = _$2(document.createElement("textarea"));
    const convertCustomSelectionsToJSONString = ({
      customSelectionsStorage
    }) => {
      return JSON.stringify(customSelectionsStorage.map(({
        name: name2,
        exerciseID,
        sections
      }) => {
        return {
          name: name2,
          exerciseID,
          exerciseTitle: getTitleFromExerciseID({
            exerciseID,
            sectionSelectionContext
          }),
          sections
        };
      }));
    };
    function closeDialogue() {
      setCurrentView(null);
      sectionSelectionContext.setDialogueCustomSelectionsStorageClosed();
    }
    function onClickCustomSelectionsJSONTextarea(event) {
      var _a2;
      navigator.clipboard.writeText((_a2 = event.target) == null ? void 0 : _a2.value).then(() => {
        notificationContext.setOptions({
          type: NotificationType.NOTIFICATION,
          title: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueExportExercises`),
          text: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueExportNotificationCopyToClipboard`),
          timeout: 1e3
        });
      }).catch(() => {
        notificationContext.setOptions({
          type: NotificationType.WARNING,
          title: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueExportExercises`),
          text: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueExportErrorCopyToClipboard`)
        });
      });
    }
    function onClickSaveAndImport() {
      var _a2;
      const importValue = (_a2 = textareaImportElement.current) == null ? void 0 : _a2.value;
      if (importValue && importValue.length > 0) {
        try {
          const customSelectionsImport = JSON.parse(importValue);
          let skippedImports = 0;
          let imports = 0;
          const exercisesToAdd = [];
          const customSelectionsToAdd = [];
          const findExercisesToAdd = ({
            name: name2,
            sections,
            exerciseID,
            exerciseTitle
          }) => {
            const existingCustomSelection = getCustomSelectionFromHash({
              hash: getCustomSelectionHashFromSelectionContext({
                selectedExercise: {
                  exerciseID
                },
                selectedSections: sections
              }),
              sectionSelectionContext
            });
            const existingCustomSelectionExercise = getCustomSelectionExerciseFromID({
              exerciseID,
              sectionSelectionContext
            });
            if (!existingCustomSelectionExercise && exercisesToAdd.filter(propFilterExerciseID(exerciseID)).length === 0) {
              exercisesToAdd.push({
                exerciseID,
                exerciseTitle
              });
            }
            if (!existingCustomSelection) {
              customSelectionsToAdd.push({
                exerciseID,
                name: name2,
                exerciseTitle,
                sections: sections.map(sectionsMapperRestoreElementIDs(exerciseID))
              });
              imports++;
            } else {
              skippedImports++;
            }
          };
          customSelectionsImport.forEach(findExercisesToAdd);
          sectionSelectionContext.setMultipleInCustomSelectionsExercisesStorage({
            customSelectionsExercisesStorageSetters: exercisesToAdd
          });
          sectionSelectionContext.setMultipleInCustomSelectionsStorage({
            customSelectionsStorageSetters: customSelectionsToAdd
          });
          notificationContext.setOptions({
            type: NotificationType.NOTIFICATION,
            title: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueImportExercises`),
            text: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueImportNotificationImported`, {
              count: imports
            }) + instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueImportNotificationAndSkipped`, {
              count: skippedImports
            })
          });
        } catch {
          notificationContext.setOptions({
            type: NotificationType.ERROR,
            title: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueImportExercises`),
            text: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueImportErrorFormat`)
          });
        }
      }
    }
    function viewToggler(view) {
      return () => {
        if (currentView !== view) {
          setCurrentView(view);
        } else {
          setCurrentView(null);
        }
      };
    }
    return o($5d3850c4d0b4e6c7$export$be92b6f5f03c0fe9, {
      open: sectionSelectionContext.dialogueCustomSelectionsStorageOpen,
      children: o($5d3850c4d0b4e6c7$export$602eac185826482c, {
        children: [o($5d3850c4d0b4e6c7$export$c6fdb837b070b4ff, {
          className: "DialogOverlay"
        }), o($5d3850c4d0b4e6c7$export$7c6e2c02157bb7d2, {
          className: "DialogCustomSelectionsStorage DialogContent",
          children: [o($5d3850c4d0b4e6c7$export$f99233281efd08a0, {
            className: "DialogTitle",
            children: [!currentView && instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueTitle`), currentView === "import" && instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueImportExercises`), currentView === "export" && instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueExportExercises`)]
          }), !currentView && o("div", {
            className: "DialogContentScroll",
            children: [o($5d3850c4d0b4e6c7$export$393edc798c47379d, {
              className: "DialogDescription",
              children: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueDescription`)
            }), o(SortableExercisesCollection, {})]
          }), currentView === "export" && o("div", {
            className: "DialogContentScroll",
            children: [o($5d3850c4d0b4e6c7$export$393edc798c47379d, {
              className: "DialogDescription",
              children: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueExportDescription`)
            }), o("textarea", {
              className: "Textarea",
              readOnly: true,
              value: convertCustomSelectionsToJSONString(sectionSelectionContext),
              onClick: onClickCustomSelectionsJSONTextarea
            })]
          }), currentView === "import" && o("div", {
            className: "DialogContentScroll",
            children: [o($5d3850c4d0b4e6c7$export$393edc798c47379d, {
              className: "DialogDescription",
              children: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueImportDescription`)
            }), o("textarea", {
              className: "Textarea",
              ref: textareaImportElement
            })]
          }), o("div", {
            className: "ButtonGroup",
            children: [currentView === "import" && o("button", {
              tabIndex: -1,
              className: "Button green",
              onClick: onClickSaveAndImport,
              children: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueImportSaveButton`, {
                count: 0
              })
            }), o("button", {
              tabIndex: -1,
              className: `Button ${currentView === "import" ? "blue" : "mauve"}`,
              onClick: viewToggler("import"),
              children: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueImportExercises`)
            }), o("button", {
              tabIndex: -1,
              className: `Button ${currentView === "export" ? "blue" : "mauve"}`,
              onClick: viewToggler("export"),
              children: instance.t(`${LANG_NS_MAIN}:customSelectionsStorageDialogueExportExercises`)
            })]
          }), o("button", {
            className: "IconButton",
            "aria-label": "Close",
            onClick: closeDialogue,
            children: o(Cross2Icon, {})
          })]
        })]
      })
    });
  };
  const AlertDialogue = () => {
    const alertContext = q$1(AlertContext);
    function clickCancel() {
      alertContext.options.cancelCallback();
      alertContext.setClosed();
    }
    function clickOK() {
      alertContext.options.okCallback();
      alertContext.setClosed();
    }
    return o($5d3850c4d0b4e6c7$export$be92b6f5f03c0fe9, {
      open: alertContext.open,
      children: o($5d3850c4d0b4e6c7$export$602eac185826482c, {
        children: [o($5d3850c4d0b4e6c7$export$c6fdb837b070b4ff, {
          className: "DialogOverlay Alert"
        }), o($5d3850c4d0b4e6c7$export$7c6e2c02157bb7d2, {
          className: "DialogContent Alert",
          children: [o($5d3850c4d0b4e6c7$export$f99233281efd08a0, {
            className: "DialogTitle",
            children: alertContext.options.title
          }), o("div", {
            className: "DialogContentScroll",
            children: o($5d3850c4d0b4e6c7$export$393edc798c47379d, {
              className: "DialogDescription",
              children: alertContext.options.text
            })
          }), o("div", {
            className: "ButtonGroup",
            children: [o("button", {
              className: "Button mauve",
              onClick: clickCancel,
              children: alertContext.options.cancelButtonText
            }), o("button", {
              className: "Button blue",
              onClick: clickOK,
              children: alertContext.options.okButtonText
            })]
          }), o("button", {
            className: "IconButton",
            "aria-label": "Close",
            onClick: alertContext.setClosed,
            children: o(Cross2Icon, {})
          })]
        })]
      })
    });
  };
  var lodash = { exports: {} };
  /**
   * @license
   * Lodash <https://lodash.com/>
   * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
   * Released under MIT license <https://lodash.com/license>
   * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
   * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
   */
  lodash.exports;
  (function(module, exports) {
    (function() {
      var undefined$1;
      var VERSION = "4.17.21";
      var LARGE_ARRAY_SIZE = 200;
      var CORE_ERROR_TEXT = "Unsupported core-js use. Try https://npms.io/search?q=ponyfill.", FUNC_ERROR_TEXT = "Expected a function", INVALID_TEMPL_VAR_ERROR_TEXT = "Invalid `variable` option passed into `_.template`";
      var HASH_UNDEFINED = "__lodash_hash_undefined__";
      var MAX_MEMOIZE_SIZE = 500;
      var PLACEHOLDER = "__lodash_placeholder__";
      var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4;
      var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2;
      var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512;
      var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "...";
      var HOT_COUNT = 800, HOT_SPAN = 16;
      var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3;
      var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 17976931348623157e292, NAN = 0 / 0;
      var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
      var wrapFlags = [
        ["ary", WRAP_ARY_FLAG],
        ["bind", WRAP_BIND_FLAG],
        ["bindKey", WRAP_BIND_KEY_FLAG],
        ["curry", WRAP_CURRY_FLAG],
        ["curryRight", WRAP_CURRY_RIGHT_FLAG],
        ["flip", WRAP_FLIP_FLAG],
        ["partial", WRAP_PARTIAL_FLAG],
        ["partialRight", WRAP_PARTIAL_RIGHT_FLAG],
        ["rearg", WRAP_REARG_FLAG]
      ];
      var argsTag = "[object Arguments]", arrayTag = "[object Array]", asyncTag = "[object AsyncFunction]", boolTag = "[object Boolean]", dateTag = "[object Date]", domExcTag = "[object DOMException]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", nullTag = "[object Null]", objectTag = "[object Object]", promiseTag = "[object Promise]", proxyTag = "[object Proxy]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", undefinedTag = "[object Undefined]", weakMapTag = "[object WeakMap]", weakSetTag = "[object WeakSet]";
      var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]";
      var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
      var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
      var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g;
      var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
      var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source);
      var reTrimStart = /^\s+/;
      var reWhitespace = /\s/;
      var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /;
      var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
      var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/;
      var reEscapeChar = /\\(\\)?/g;
      var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
      var reFlags = /\w*$/;
      var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
      var reIsBinary = /^0b[01]+$/i;
      var reIsHostCtor = /^\[object .+?Constructor\]$/;
      var reIsOctal = /^0o[0-7]+$/i;
      var reIsUint = /^(?:0|[1-9]\d*)$/;
      var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
      var reNoMatch = /($^)/;
      var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
      var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f", reComboHalfMarksRange = "\\ufe20-\\ufe2f", rsComboSymbolsRange = "\\u20d0-\\u20ff", rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = "\\u2700-\\u27bf", rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange = "\\u2000-\\u206f", rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange = "\\ufe0e\\ufe0f", rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
      var rsApos = "['’]", rsAstral = "[" + rsAstralRange + "]", rsBreak = "[" + rsBreakRange + "]", rsCombo = "[" + rsComboRange + "]", rsDigits = "\\d+", rsDingbat = "[" + rsDingbatRange + "]", rsLower = "[" + rsLowerRange + "]", rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper = "[" + rsUpperRange + "]", rsZWJ = "\\u200d";
      var rsMiscLower = "(?:" + rsLower + "|" + rsMisc + ")", rsMiscUpper = "(?:" + rsUpper + "|" + rsMisc + ")", rsOptContrLower = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?", rsOptContrUpper = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*", rsOrdLower = "\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])", rsOrdUpper = "\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq, rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")";
      var reApos = RegExp(rsApos, "g");
      var reComboMark = RegExp(rsCombo, "g");
      var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g");
      var reUnicodeWord = RegExp([
        rsUpper + "?" + rsLower + "+" + rsOptContrLower + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")",
        rsMiscUpper + "+" + rsOptContrUpper + "(?=" + [rsBreak, rsUpper + rsMiscLower, "$"].join("|") + ")",
        rsUpper + "?" + rsMiscLower + "+" + rsOptContrLower,
        rsUpper + "+" + rsOptContrUpper,
        rsOrdUpper,
        rsOrdLower,
        rsDigits,
        rsEmoji
      ].join("|"), "g");
      var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + "]");
      var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
      var contextProps = [
        "Array",
        "Buffer",
        "DataView",
        "Date",
        "Error",
        "Float32Array",
        "Float64Array",
        "Function",
        "Int8Array",
        "Int16Array",
        "Int32Array",
        "Map",
        "Math",
        "Object",
        "Promise",
        "RegExp",
        "Set",
        "String",
        "Symbol",
        "TypeError",
        "Uint8Array",
        "Uint8ClampedArray",
        "Uint16Array",
        "Uint32Array",
        "WeakMap",
        "_",
        "clearTimeout",
        "isFinite",
        "parseInt",
        "setTimeout"
      ];
      var templateCounter = -1;
      var typedArrayTags = {};
      typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
      typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
      var cloneableTags = {};
      cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
      cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false;
      var deburredLetters = {
        // Latin-1 Supplement block.
        "À": "A",
        "Á": "A",
        "Â": "A",
        "Ã": "A",
        "Ä": "A",
        "Å": "A",
        "à": "a",
        "á": "a",
        "â": "a",
        "ã": "a",
        "ä": "a",
        "å": "a",
        "Ç": "C",
        "ç": "c",
        "Ð": "D",
        "ð": "d",
        "È": "E",
        "É": "E",
        "Ê": "E",
        "Ë": "E",
        "è": "e",
        "é": "e",
        "ê": "e",
        "ë": "e",
        "Ì": "I",
        "Í": "I",
        "Î": "I",
        "Ï": "I",
        "ì": "i",
        "í": "i",
        "î": "i",
        "ï": "i",
        "Ñ": "N",
        "ñ": "n",
        "Ò": "O",
        "Ó": "O",
        "Ô": "O",
        "Õ": "O",
        "Ö": "O",
        "Ø": "O",
        "ò": "o",
        "ó": "o",
        "ô": "o",
        "õ": "o",
        "ö": "o",
        "ø": "o",
        "Ù": "U",
        "Ú": "U",
        "Û": "U",
        "Ü": "U",
        "ù": "u",
        "ú": "u",
        "û": "u",
        "ü": "u",
        "Ý": "Y",
        "ý": "y",
        "ÿ": "y",
        "Æ": "Ae",
        "æ": "ae",
        "Þ": "Th",
        "þ": "th",
        "ß": "ss",
        // Latin Extended-A block.
        "Ā": "A",
        "Ă": "A",
        "Ą": "A",
        "ā": "a",
        "ă": "a",
        "ą": "a",
        "Ć": "C",
        "Ĉ": "C",
        "Ċ": "C",
        "Č": "C",
        "ć": "c",
        "ĉ": "c",
        "ċ": "c",
        "č": "c",
        "Ď": "D",
        "Đ": "D",
        "ď": "d",
        "đ": "d",
        "Ē": "E",
        "Ĕ": "E",
        "Ė": "E",
        "Ę": "E",
        "Ě": "E",
        "ē": "e",
        "ĕ": "e",
        "ė": "e",
        "ę": "e",
        "ě": "e",
        "Ĝ": "G",
        "Ğ": "G",
        "Ġ": "G",
        "Ģ": "G",
        "ĝ": "g",
        "ğ": "g",
        "ġ": "g",
        "ģ": "g",
        "Ĥ": "H",
        "Ħ": "H",
        "ĥ": "h",
        "ħ": "h",
        "Ĩ": "I",
        "Ī": "I",
        "Ĭ": "I",
        "Į": "I",
        "İ": "I",
        "ĩ": "i",
        "ī": "i",
        "ĭ": "i",
        "į": "i",
        "ı": "i",
        "Ĵ": "J",
        "ĵ": "j",
        "Ķ": "K",
        "ķ": "k",
        "ĸ": "k",
        "Ĺ": "L",
        "Ļ": "L",
        "Ľ": "L",
        "Ŀ": "L",
        "Ł": "L",
        "ĺ": "l",
        "ļ": "l",
        "ľ": "l",
        "ŀ": "l",
        "ł": "l",
        "Ń": "N",
        "Ņ": "N",
        "Ň": "N",
        "Ŋ": "N",
        "ń": "n",
        "ņ": "n",
        "ň": "n",
        "ŋ": "n",
        "Ō": "O",
        "Ŏ": "O",
        "Ő": "O",
        "ō": "o",
        "ŏ": "o",
        "ő": "o",
        "Ŕ": "R",
        "Ŗ": "R",
        "Ř": "R",
        "ŕ": "r",
        "ŗ": "r",
        "ř": "r",
        "Ś": "S",
        "Ŝ": "S",
        "Ş": "S",
        "Š": "S",
        "ś": "s",
        "ŝ": "s",
        "ş": "s",
        "š": "s",
        "Ţ": "T",
        "Ť": "T",
        "Ŧ": "T",
        "ţ": "t",
        "ť": "t",
        "ŧ": "t",
        "Ũ": "U",
        "Ū": "U",
        "Ŭ": "U",
        "Ů": "U",
        "Ű": "U",
        "Ų": "U",
        "ũ": "u",
        "ū": "u",
        "ŭ": "u",
        "ů": "u",
        "ű": "u",
        "ų": "u",
        "Ŵ": "W",
        "ŵ": "w",
        "Ŷ": "Y",
        "ŷ": "y",
        "Ÿ": "Y",
        "Ź": "Z",
        "Ż": "Z",
        "Ž": "Z",
        "ź": "z",
        "ż": "z",
        "ž": "z",
        "IJ": "IJ",
        "ij": "ij",
        "Œ": "Oe",
        "œ": "oe",
        "ʼn": "'n",
        "ſ": "s"
      };
      var htmlEscapes = {
        "&": "&amp;",
        "<": "&lt;",
        ">": "&gt;",
        '"': "&quot;",
        "'": "&#39;"
      };
      var htmlUnescapes = {
        "&amp;": "&",
        "&lt;": "<",
        "&gt;": ">",
        "&quot;": '"',
        "&#39;": "'"
      };
      var stringEscapes = {
        "\\": "\\",
        "'": "'",
        "\n": "n",
        "\r": "r",
        "\u2028": "u2028",
        "\u2029": "u2029"
      };
      var freeParseFloat = parseFloat, freeParseInt = parseInt;
      var freeGlobal = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal;
      var freeSelf = typeof self == "object" && self && self.Object === Object && self;
      var root = freeGlobal || freeSelf || Function("return this")();
      var freeExports = exports && !exports.nodeType && exports;
      var freeModule = freeExports && true && module && !module.nodeType && module;
      var moduleExports = freeModule && freeModule.exports === freeExports;
      var freeProcess = moduleExports && freeGlobal.process;
      var nodeUtil = function() {
        try {
          var types = freeModule && freeModule.require && freeModule.require("util").types;
          if (types) {
            return types;
          }
          return freeProcess && freeProcess.binding && freeProcess.binding("util");
        } catch (e2) {
        }
      }();
      var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
      function apply(func, thisArg, args) {
        switch (args.length) {
          case 0:
            return func.call(thisArg);
          case 1:
            return func.call(thisArg, args[0]);
          case 2:
            return func.call(thisArg, args[0], args[1]);
          case 3:
            return func.call(thisArg, args[0], args[1], args[2]);
        }
        return func.apply(thisArg, args);
      }
      function arrayAggregator(array, setter, iteratee, accumulator) {
        var index2 = -1, length = array == null ? 0 : array.length;
        while (++index2 < length) {
          var value = array[index2];
          setter(accumulator, value, iteratee(value), array);
        }
        return accumulator;
      }
      function arrayEach(array, iteratee) {
        var index2 = -1, length = array == null ? 0 : array.length;
        while (++index2 < length) {
          if (iteratee(array[index2], index2, array) === false) {
            break;
          }
        }
        return array;
      }
      function arrayEachRight(array, iteratee) {
        var length = array == null ? 0 : array.length;
        while (length--) {
          if (iteratee(array[length], length, array) === false) {
            break;
          }
        }
        return array;
      }
      function arrayEvery(array, predicate) {
        var index2 = -1, length = array == null ? 0 : array.length;
        while (++index2 < length) {
          if (!predicate(array[index2], index2, array)) {
            return false;
          }
        }
        return true;
      }
      function arrayFilter(array, predicate) {
        var index2 = -1, length = array == null ? 0 : array.length, resIndex = 0, result = [];
        while (++index2 < length) {
          var value = array[index2];
          if (predicate(value, index2, array)) {
            result[resIndex++] = value;
          }
        }
        return result;
      }
      function arrayIncludes(array, value) {
        var length = array == null ? 0 : array.length;
        return !!length && baseIndexOf(array, value, 0) > -1;
      }
      function arrayIncludesWith(array, value, comparator) {
        var index2 = -1, length = array == null ? 0 : array.length;
        while (++index2 < length) {
          if (comparator(value, array[index2])) {
            return true;
          }
        }
        return false;
      }
      function arrayMap(array, iteratee) {
        var index2 = -1, length = array == null ? 0 : array.length, result = Array(length);
        while (++index2 < length) {
          result[index2] = iteratee(array[index2], index2, array);
        }
        return result;
      }
      function arrayPush(array, values) {
        var index2 = -1, length = values.length, offset = array.length;
        while (++index2 < length) {
          array[offset + index2] = values[index2];
        }
        return array;
      }
      function arrayReduce(array, iteratee, accumulator, initAccum) {
        var index2 = -1, length = array == null ? 0 : array.length;
        if (initAccum && length) {
          accumulator = array[++index2];
        }
        while (++index2 < length) {
          accumulator = iteratee(accumulator, array[index2], index2, array);
        }
        return accumulator;
      }
      function arrayReduceRight(array, iteratee, accumulator, initAccum) {
        var length = array == null ? 0 : array.length;
        if (initAccum && length) {
          accumulator = array[--length];
        }
        while (length--) {
          accumulator = iteratee(accumulator, array[length], length, array);
        }
        return accumulator;
      }
      function arraySome(array, predicate) {
        var index2 = -1, length = array == null ? 0 : array.length;
        while (++index2 < length) {
          if (predicate(array[index2], index2, array)) {
            return true;
          }
        }
        return false;
      }
      var asciiSize = baseProperty("length");
      function asciiToArray(string) {
        return string.split("");
      }
      function asciiWords(string) {
        return string.match(reAsciiWord) || [];
      }
      function baseFindKey(collection, predicate, eachFunc) {
        var result;
        eachFunc(collection, function(value, key, collection2) {
          if (predicate(value, key, collection2)) {
            result = key;
            return false;
          }
        });
        return result;
      }
      function baseFindIndex(array, predicate, fromIndex, fromRight) {
        var length = array.length, index2 = fromIndex + (fromRight ? 1 : -1);
        while (fromRight ? index2-- : ++index2 < length) {
          if (predicate(array[index2], index2, array)) {
            return index2;
          }
        }
        return -1;
      }
      function baseIndexOf(array, value, fromIndex) {
        return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex);
      }
      function baseIndexOfWith(array, value, fromIndex, comparator) {
        var index2 = fromIndex - 1, length = array.length;
        while (++index2 < length) {
          if (comparator(array[index2], value)) {
            return index2;
          }
        }
        return -1;
      }
      function baseIsNaN(value) {
        return value !== value;
      }
      function baseMean(array, iteratee) {
        var length = array == null ? 0 : array.length;
        return length ? baseSum(array, iteratee) / length : NAN;
      }
      function baseProperty(key) {
        return function(object) {
          return object == null ? undefined$1 : object[key];
        };
      }
      function basePropertyOf(object) {
        return function(key) {
          return object == null ? undefined$1 : object[key];
        };
      }
      function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
        eachFunc(collection, function(value, index2, collection2) {
          accumulator = initAccum ? (initAccum = false, value) : iteratee(accumulator, value, index2, collection2);
        });
        return accumulator;
      }
      function baseSortBy(array, comparer) {
        var length = array.length;
        array.sort(comparer);
        while (length--) {
          array[length] = array[length].value;
        }
        return array;
      }
      function baseSum(array, iteratee) {
        var result, index2 = -1, length = array.length;
        while (++index2 < length) {
          var current = iteratee(array[index2]);
          if (current !== undefined$1) {
            result = result === undefined$1 ? current : result + current;
          }
        }
        return result;
      }
      function baseTimes(n2, iteratee) {
        var index2 = -1, result = Array(n2);
        while (++index2 < n2) {
          result[index2] = iteratee(index2);
        }
        return result;
      }
      function baseToPairs(object, props) {
        return arrayMap(props, function(key) {
          return [key, object[key]];
        });
      }
      function baseTrim(string) {
        return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, "") : string;
      }
      function baseUnary(func) {
        return function(value) {
          return func(value);
        };
      }
      function baseValues(object, props) {
        return arrayMap(props, function(key) {
          return object[key];
        });
      }
      function cacheHas(cache, key) {
        return cache.has(key);
      }
      function charsStartIndex(strSymbols, chrSymbols) {
        var index2 = -1, length = strSymbols.length;
        while (++index2 < length && baseIndexOf(chrSymbols, strSymbols[index2], 0) > -1) {
        }
        return index2;
      }
      function charsEndIndex(strSymbols, chrSymbols) {
        var index2 = strSymbols.length;
        while (index2-- && baseIndexOf(chrSymbols, strSymbols[index2], 0) > -1) {
        }
        return index2;
      }
      function countHolders(array, placeholder) {
        var length = array.length, result = 0;
        while (length--) {
          if (array[length] === placeholder) {
            ++result;
          }
        }
        return result;
      }
      var deburrLetter = basePropertyOf(deburredLetters);
      var escapeHtmlChar = basePropertyOf(htmlEscapes);
      function escapeStringChar(chr) {
        return "\\" + stringEscapes[chr];
      }
      function getValue(object, key) {
        return object == null ? undefined$1 : object[key];
      }
      function hasUnicode(string) {
        return reHasUnicode.test(string);
      }
      function hasUnicodeWord(string) {
        return reHasUnicodeWord.test(string);
      }
      function iteratorToArray(iterator) {
        var data, result = [];
        while (!(data = iterator.next()).done) {
          result.push(data.value);
        }
        return result;
      }
      function mapToArray(map2) {
        var index2 = -1, result = Array(map2.size);
        map2.forEach(function(value, key) {
          result[++index2] = [key, value];
        });
        return result;
      }
      function overArg(func, transform) {
        return function(arg) {
          return func(transform(arg));
        };
      }
      function replaceHolders(array, placeholder) {
        var index2 = -1, length = array.length, resIndex = 0, result = [];
        while (++index2 < length) {
          var value = array[index2];
          if (value === placeholder || value === PLACEHOLDER) {
            array[index2] = PLACEHOLDER;
            result[resIndex++] = index2;
          }
        }
        return result;
      }
      function setToArray(set2) {
        var index2 = -1, result = Array(set2.size);
        set2.forEach(function(value) {
          result[++index2] = value;
        });
        return result;
      }
      function setToPairs(set2) {
        var index2 = -1, result = Array(set2.size);
        set2.forEach(function(value) {
          result[++index2] = [value, value];
        });
        return result;
      }
      function strictIndexOf(array, value, fromIndex) {
        var index2 = fromIndex - 1, length = array.length;
        while (++index2 < length) {
          if (array[index2] === value) {
            return index2;
          }
        }
        return -1;
      }
      function strictLastIndexOf(array, value, fromIndex) {
        var index2 = fromIndex + 1;
        while (index2--) {
          if (array[index2] === value) {
            return index2;
          }
        }
        return index2;
      }
      function stringSize(string) {
        return hasUnicode(string) ? unicodeSize(string) : asciiSize(string);
      }
      function stringToArray(string) {
        return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string);
      }
      function trimmedEndIndex(string) {
        var index2 = string.length;
        while (index2-- && reWhitespace.test(string.charAt(index2))) {
        }
        return index2;
      }
      var unescapeHtmlChar = basePropertyOf(htmlUnescapes);
      function unicodeSize(string) {
        var result = reUnicode.lastIndex = 0;
        while (reUnicode.test(string)) {
          ++result;
        }
        return result;
      }
      function unicodeToArray(string) {
        return string.match(reUnicode) || [];
      }
      function unicodeWords(string) {
        return string.match(reUnicodeWord) || [];
      }
      var runInContext = function runInContext2(context) {
        context = context == null ? root : _2.defaults(root.Object(), context, _2.pick(root, contextProps));
        var Array2 = context.Array, Date2 = context.Date, Error2 = context.Error, Function2 = context.Function, Math2 = context.Math, Object2 = context.Object, RegExp2 = context.RegExp, String2 = context.String, TypeError2 = context.TypeError;
        var arrayProto = Array2.prototype, funcProto = Function2.prototype, objectProto = Object2.prototype;
        var coreJsData = context["__core-js_shared__"];
        var funcToString = funcProto.toString;
        var hasOwnProperty = objectProto.hasOwnProperty;
        var idCounter2 = 0;
        var maskSrcKey = function() {
          var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
          return uid ? "Symbol(src)_1." + uid : "";
        }();
        var nativeObjectToString = objectProto.toString;
        var objectCtorString = funcToString.call(Object2);
        var oldDash = root._;
        var reIsNative = RegExp2(
          "^" + funcToString.call(hasOwnProperty).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
        );
        var Buffer2 = moduleExports ? context.Buffer : undefined$1, Symbol2 = context.Symbol, Uint8Array2 = context.Uint8Array, allocUnsafe = Buffer2 ? Buffer2.allocUnsafe : undefined$1, getPrototype = overArg(Object2.getPrototypeOf, Object2), objectCreate = Object2.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol2 ? Symbol2.isConcatSpreadable : undefined$1, symIterator = Symbol2 ? Symbol2.iterator : undefined$1, symToStringTag = Symbol2 ? Symbol2.toStringTag : undefined$1;
        var defineProperty = function() {
          try {
            var func = getNative(Object2, "defineProperty");
            func({}, "", {});
            return func;
          } catch (e2) {
          }
        }();
        var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date2 && Date2.now !== root.Date.now && Date2.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;
        var nativeCeil = Math2.ceil, nativeFloor = Math2.floor, nativeGetSymbols = Object2.getOwnPropertySymbols, nativeIsBuffer = Buffer2 ? Buffer2.isBuffer : undefined$1, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object2.keys, Object2), nativeMax = Math2.max, nativeMin = Math2.min, nativeNow = Date2.now, nativeParseInt = context.parseInt, nativeRandom = Math2.random, nativeReverse = arrayProto.reverse;
        var DataView = getNative(context, "DataView"), Map2 = getNative(context, "Map"), Promise2 = getNative(context, "Promise"), Set2 = getNative(context, "Set"), WeakMap2 = getNative(context, "WeakMap"), nativeCreate = getNative(Object2, "create");
        var metaMap = WeakMap2 && new WeakMap2();
        var realNames = {};
        var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map2), promiseCtorString = toSource(Promise2), setCtorString = toSource(Set2), weakMapCtorString = toSource(WeakMap2);
        var symbolProto = Symbol2 ? Symbol2.prototype : undefined$1, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined$1, symbolToString = symbolProto ? symbolProto.toString : undefined$1;
        function lodash2(value) {
          if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
            if (value instanceof LodashWrapper) {
              return value;
            }
            if (hasOwnProperty.call(value, "__wrapped__")) {
              return wrapperClone(value);
            }
          }
          return new LodashWrapper(value);
        }
        var baseCreate = function() {
          function object() {
          }
          return function(proto) {
            if (!isObject2(proto)) {
              return {};
            }
            if (objectCreate) {
              return objectCreate(proto);
            }
            object.prototype = proto;
            var result2 = new object();
            object.prototype = undefined$1;
            return result2;
          };
        }();
        function baseLodash() {
        }
        function LodashWrapper(value, chainAll) {
          this.__wrapped__ = value;
          this.__actions__ = [];
          this.__chain__ = !!chainAll;
          this.__index__ = 0;
          this.__values__ = undefined$1;
        }
        lodash2.templateSettings = {
          /**
           * Used to detect `data` property values to be HTML-escaped.
           *
           * @memberOf _.templateSettings
           * @type {RegExp}
           */
          "escape": reEscape,
          /**
           * Used to detect code to be evaluated.
           *
           * @memberOf _.templateSettings
           * @type {RegExp}
           */
          "evaluate": reEvaluate,
          /**
           * Used to detect `data` property values to inject.
           *
           * @memberOf _.templateSettings
           * @type {RegExp}
           */
          "interpolate": reInterpolate,
          /**
           * Used to reference the data object in the template text.
           *
           * @memberOf _.templateSettings
           * @type {string}
           */
          "variable": "",
          /**
           * Used to import variables into the compiled template.
           *
           * @memberOf _.templateSettings
           * @type {Object}
           */
          "imports": {
            /**
             * A reference to the `lodash` function.
             *
             * @memberOf _.templateSettings.imports
             * @type {Function}
             */
            "_": lodash2
          }
        };
        lodash2.prototype = baseLodash.prototype;
        lodash2.prototype.constructor = lodash2;
        LodashWrapper.prototype = baseCreate(baseLodash.prototype);
        LodashWrapper.prototype.constructor = LodashWrapper;
        function LazyWrapper(value) {
          this.__wrapped__ = value;
          this.__actions__ = [];
          this.__dir__ = 1;
          this.__filtered__ = false;
          this.__iteratees__ = [];
          this.__takeCount__ = MAX_ARRAY_LENGTH;
          this.__views__ = [];
        }
        function lazyClone() {
          var result2 = new LazyWrapper(this.__wrapped__);
          result2.__actions__ = copyArray(this.__actions__);
          result2.__dir__ = this.__dir__;
          result2.__filtered__ = this.__filtered__;
          result2.__iteratees__ = copyArray(this.__iteratees__);
          result2.__takeCount__ = this.__takeCount__;
          result2.__views__ = copyArray(this.__views__);
          return result2;
        }
        function lazyReverse() {
          if (this.__filtered__) {
            var result2 = new LazyWrapper(this);
            result2.__dir__ = -1;
            result2.__filtered__ = true;
          } else {
            result2 = this.clone();
            result2.__dir__ *= -1;
          }
          return result2;
        }
        function lazyValue() {
          var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index2 = isRight ? end : start - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__);
          if (!isArr || !isRight && arrLength == length && takeCount == length) {
            return baseWrapperValue(array, this.__actions__);
          }
          var result2 = [];
          outer:
            while (length-- && resIndex < takeCount) {
              index2 += dir;
              var iterIndex = -1, value = array[index2];
              while (++iterIndex < iterLength) {
                var data = iteratees[iterIndex], iteratee2 = data.iteratee, type = data.type, computed = iteratee2(value);
                if (type == LAZY_MAP_FLAG) {
                  value = computed;
                } else if (!computed) {
                  if (type == LAZY_FILTER_FLAG) {
                    continue outer;
                  } else {
                    break outer;
                  }
                }
              }
              result2[resIndex++] = value;
            }
          return result2;
        }
        LazyWrapper.prototype = baseCreate(baseLodash.prototype);
        LazyWrapper.prototype.constructor = LazyWrapper;
        function Hash(entries) {
          var index2 = -1, length = entries == null ? 0 : entries.length;
          this.clear();
          while (++index2 < length) {
            var entry = entries[index2];
            this.set(entry[0], entry[1]);
          }
        }
        function hashClear() {
          this.__data__ = nativeCreate ? nativeCreate(null) : {};
          this.size = 0;
        }
        function hashDelete(key) {
          var result2 = this.has(key) && delete this.__data__[key];
          this.size -= result2 ? 1 : 0;
          return result2;
        }
        function hashGet(key) {
          var data = this.__data__;
          if (nativeCreate) {
            var result2 = data[key];
            return result2 === HASH_UNDEFINED ? undefined$1 : result2;
          }
          return hasOwnProperty.call(data, key) ? data[key] : undefined$1;
        }
        function hashHas(key) {
          var data = this.__data__;
          return nativeCreate ? data[key] !== undefined$1 : hasOwnProperty.call(data, key);
        }
        function hashSet(key, value) {
          var data = this.__data__;
          this.size += this.has(key) ? 0 : 1;
          data[key] = nativeCreate && value === undefined$1 ? HASH_UNDEFINED : value;
          return this;
        }
        Hash.prototype.clear = hashClear;
        Hash.prototype["delete"] = hashDelete;
        Hash.prototype.get = hashGet;
        Hash.prototype.has = hashHas;
        Hash.prototype.set = hashSet;
        function ListCache(entries) {
          var index2 = -1, length = entries == null ? 0 : entries.length;
          this.clear();
          while (++index2 < length) {
            var entry = entries[index2];
            this.set(entry[0], entry[1]);
          }
        }
        function listCacheClear() {
          this.__data__ = [];
          this.size = 0;
        }
        function listCacheDelete(key) {
          var data = this.__data__, index2 = assocIndexOf(data, key);
          if (index2 < 0) {
            return false;
          }
          var lastIndex = data.length - 1;
          if (index2 == lastIndex) {
            data.pop();
          } else {
            splice.call(data, index2, 1);
          }
          --this.size;
          return true;
        }
        function listCacheGet(key) {
          var data = this.__data__, index2 = assocIndexOf(data, key);
          return index2 < 0 ? undefined$1 : data[index2][1];
        }
        function listCacheHas(key) {
          return assocIndexOf(this.__data__, key) > -1;
        }
        function listCacheSet(key, value) {
          var data = this.__data__, index2 = assocIndexOf(data, key);
          if (index2 < 0) {
            ++this.size;
            data.push([key, value]);
          } else {
            data[index2][1] = value;
          }
          return this;
        }
        ListCache.prototype.clear = listCacheClear;
        ListCache.prototype["delete"] = listCacheDelete;
        ListCache.prototype.get = listCacheGet;
        ListCache.prototype.has = listCacheHas;
        ListCache.prototype.set = listCacheSet;
        function MapCache(entries) {
          var index2 = -1, length = entries == null ? 0 : entries.length;
          this.clear();
          while (++index2 < length) {
            var entry = entries[index2];
            this.set(entry[0], entry[1]);
          }
        }
        function mapCacheClear() {
          this.size = 0;
          this.__data__ = {
            "hash": new Hash(),
            "map": new (Map2 || ListCache)(),
            "string": new Hash()
          };
        }
        function mapCacheDelete(key) {
          var result2 = getMapData(this, key)["delete"](key);
          this.size -= result2 ? 1 : 0;
          return result2;
        }
        function mapCacheGet(key) {
          return getMapData(this, key).get(key);
        }
        function mapCacheHas(key) {
          return getMapData(this, key).has(key);
        }
        function mapCacheSet(key, value) {
          var data = getMapData(this, key), size2 = data.size;
          data.set(key, value);
          this.size += data.size == size2 ? 0 : 1;
          return this;
        }
        MapCache.prototype.clear = mapCacheClear;
        MapCache.prototype["delete"] = mapCacheDelete;
        MapCache.prototype.get = mapCacheGet;
        MapCache.prototype.has = mapCacheHas;
        MapCache.prototype.set = mapCacheSet;
        function SetCache(values2) {
          var index2 = -1, length = values2 == null ? 0 : values2.length;
          this.__data__ = new MapCache();
          while (++index2 < length) {
            this.add(values2[index2]);
          }
        }
        function setCacheAdd(value) {
          this.__data__.set(value, HASH_UNDEFINED);
          return this;
        }
        function setCacheHas(value) {
          return this.__data__.has(value);
        }
        SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
        SetCache.prototype.has = setCacheHas;
        function Stack(entries) {
          var data = this.__data__ = new ListCache(entries);
          this.size = data.size;
        }
        function stackClear() {
          this.__data__ = new ListCache();
          this.size = 0;
        }
        function stackDelete(key) {
          var data = this.__data__, result2 = data["delete"](key);
          this.size = data.size;
          return result2;
        }
        function stackGet(key) {
          return this.__data__.get(key);
        }
        function stackHas(key) {
          return this.__data__.has(key);
        }
        function stackSet(key, value) {
          var data = this.__data__;
          if (data instanceof ListCache) {
            var pairs = data.__data__;
            if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) {
              pairs.push([key, value]);
              this.size = ++data.size;
              return this;
            }
            data = this.__data__ = new MapCache(pairs);
          }
          data.set(key, value);
          this.size = data.size;
          return this;
        }
        Stack.prototype.clear = stackClear;
        Stack.prototype["delete"] = stackDelete;
        Stack.prototype.get = stackGet;
        Stack.prototype.has = stackHas;
        Stack.prototype.set = stackSet;
        function arrayLikeKeys(value, inherited) {
          var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result2 = skipIndexes ? baseTimes(value.length, String2) : [], length = result2.length;
          for (var key in value) {
            if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode.
            (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers.
            isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays.
            isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties.
            isIndex(key, length)))) {
              result2.push(key);
            }
          }
          return result2;
        }
        function arraySample(array) {
          var length = array.length;
          return length ? array[baseRandom(0, length - 1)] : undefined$1;
        }
        function arraySampleSize(array, n2) {
          return shuffleSelf(copyArray(array), baseClamp(n2, 0, array.length));
        }
        function arrayShuffle(array) {
          return shuffleSelf(copyArray(array));
        }
        function assignMergeValue(object, key, value) {
          if (value !== undefined$1 && !eq(object[key], value) || value === undefined$1 && !(key in object)) {
            baseAssignValue(object, key, value);
          }
        }
        function assignValue(object, key, value) {
          var objValue = object[key];
          if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || value === undefined$1 && !(key in object)) {
            baseAssignValue(object, key, value);
          }
        }
        function assocIndexOf(array, key) {
          var length = array.length;
          while (length--) {
            if (eq(array[length][0], key)) {
              return length;
            }
          }
          return -1;
        }
        function baseAggregator(collection, setter, iteratee2, accumulator) {
          baseEach(collection, function(value, key, collection2) {
            setter(accumulator, value, iteratee2(value), collection2);
          });
          return accumulator;
        }
        function baseAssign(object, source) {
          return object && copyObject(source, keys(source), object);
        }
        function baseAssignIn(object, source) {
          return object && copyObject(source, keysIn(source), object);
        }
        function baseAssignValue(object, key, value) {
          if (key == "__proto__" && defineProperty) {
            defineProperty(object, key, {
              "configurable": true,
              "enumerable": true,
              "value": value,
              "writable": true
            });
          } else {
            object[key] = value;
          }
        }
        function baseAt(object, paths) {
          var index2 = -1, length = paths.length, result2 = Array2(length), skip = object == null;
          while (++index2 < length) {
            result2[index2] = skip ? undefined$1 : get2(object, paths[index2]);
          }
          return result2;
        }
        function baseClamp(number, lower, upper) {
          if (number === number) {
            if (upper !== undefined$1) {
              number = number <= upper ? number : upper;
            }
            if (lower !== undefined$1) {
              number = number >= lower ? number : lower;
            }
          }
          return number;
        }
        function baseClone(value, bitmask, customizer, key, object, stack) {
          var result2, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG;
          if (customizer) {
            result2 = object ? customizer(value, key, object, stack) : customizer(value);
          }
          if (result2 !== undefined$1) {
            return result2;
          }
          if (!isObject2(value)) {
            return value;
          }
          var isArr = isArray(value);
          if (isArr) {
            result2 = initCloneArray(value);
            if (!isDeep) {
              return copyArray(value, result2);
            }
          } else {
            var tag = getTag(value), isFunc = tag == funcTag || tag == genTag;
            if (isBuffer(value)) {
              return cloneBuffer(value, isDeep);
            }
            if (tag == objectTag || tag == argsTag || isFunc && !object) {
              result2 = isFlat || isFunc ? {} : initCloneObject(value);
              if (!isDeep) {
                return isFlat ? copySymbolsIn(value, baseAssignIn(result2, value)) : copySymbols(value, baseAssign(result2, value));
              }
            } else {
              if (!cloneableTags[tag]) {
                return object ? value : {};
              }
              result2 = initCloneByTag(value, tag, isDeep);
            }
          }
          stack || (stack = new Stack());
          var stacked = stack.get(value);
          if (stacked) {
            return stacked;
          }
          stack.set(value, result2);
          if (isSet(value)) {
            value.forEach(function(subValue) {
              result2.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
            });
          } else if (isMap(value)) {
            value.forEach(function(subValue, key2) {
              result2.set(key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
            });
          }
          var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys;
          var props = isArr ? undefined$1 : keysFunc(value);
          arrayEach(props || value, function(subValue, key2) {
            if (props) {
              key2 = subValue;
              subValue = value[key2];
            }
            assignValue(result2, key2, baseClone(subValue, bitmask, customizer, key2, value, stack));
          });
          return result2;
        }
        function baseConforms(source) {
          var props = keys(source);
          return function(object) {
            return baseConformsTo(object, source, props);
          };
        }
        function baseConformsTo(object, source, props) {
          var length = props.length;
          if (object == null) {
            return !length;
          }
          object = Object2(object);
          while (length--) {
            var key = props[length], predicate = source[key], value = object[key];
            if (value === undefined$1 && !(key in object) || !predicate(value)) {
              return false;
            }
          }
          return true;
        }
        function baseDelay(func, wait, args) {
          if (typeof func != "function") {
            throw new TypeError2(FUNC_ERROR_TEXT);
          }
          return setTimeout2(function() {
            func.apply(undefined$1, args);
          }, wait);
        }
        function baseDifference(array, values2, iteratee2, comparator) {
          var index2 = -1, includes2 = arrayIncludes, isCommon = true, length = array.length, result2 = [], valuesLength = values2.length;
          if (!length) {
            return result2;
          }
          if (iteratee2) {
            values2 = arrayMap(values2, baseUnary(iteratee2));
          }
          if (comparator) {
            includes2 = arrayIncludesWith;
            isCommon = false;
          } else if (values2.length >= LARGE_ARRAY_SIZE) {
            includes2 = cacheHas;
            isCommon = false;
            values2 = new SetCache(values2);
          }
          outer:
            while (++index2 < length) {
              var value = array[index2], computed = iteratee2 == null ? value : iteratee2(value);
              value = comparator || value !== 0 ? value : 0;
              if (isCommon && computed === computed) {
                var valuesIndex = valuesLength;
                while (valuesIndex--) {
                  if (values2[valuesIndex] === computed) {
                    continue outer;
                  }
                }
                result2.push(value);
              } else if (!includes2(values2, computed, comparator)) {
                result2.push(value);
              }
            }
          return result2;
        }
        var baseEach = createBaseEach(baseForOwn);
        var baseEachRight = createBaseEach(baseForOwnRight, true);
        function baseEvery(collection, predicate) {
          var result2 = true;
          baseEach(collection, function(value, index2, collection2) {
            result2 = !!predicate(value, index2, collection2);
            return result2;
          });
          return result2;
        }
        function baseExtremum(array, iteratee2, comparator) {
          var index2 = -1, length = array.length;
          while (++index2 < length) {
            var value = array[index2], current = iteratee2(value);
            if (current != null && (computed === undefined$1 ? current === current && !isSymbol(current) : comparator(current, computed))) {
              var computed = current, result2 = value;
            }
          }
          return result2;
        }
        function baseFill(array, value, start, end) {
          var length = array.length;
          start = toInteger(start);
          if (start < 0) {
            start = -start > length ? 0 : length + start;
          }
          end = end === undefined$1 || end > length ? length : toInteger(end);
          if (end < 0) {
            end += length;
          }
          end = start > end ? 0 : toLength(end);
          while (start < end) {
            array[start++] = value;
          }
          return array;
        }
        function baseFilter(collection, predicate) {
          var result2 = [];
          baseEach(collection, function(value, index2, collection2) {
            if (predicate(value, index2, collection2)) {
              result2.push(value);
            }
          });
          return result2;
        }
        function baseFlatten(array, depth, predicate, isStrict, result2) {
          var index2 = -1, length = array.length;
          predicate || (predicate = isFlattenable);
          result2 || (result2 = []);
          while (++index2 < length) {
            var value = array[index2];
            if (depth > 0 && predicate(value)) {
              if (depth > 1) {
                baseFlatten(value, depth - 1, predicate, isStrict, result2);
              } else {
                arrayPush(result2, value);
              }
            } else if (!isStrict) {
              result2[result2.length] = value;
            }
          }
          return result2;
        }
        var baseFor = createBaseFor();
        var baseForRight = createBaseFor(true);
        function baseForOwn(object, iteratee2) {
          return object && baseFor(object, iteratee2, keys);
        }
        function baseForOwnRight(object, iteratee2) {
          return object && baseForRight(object, iteratee2, keys);
        }
        function baseFunctions(object, props) {
          return arrayFilter(props, function(key) {
            return isFunction(object[key]);
          });
        }
        function baseGet(object, path) {
          path = castPath(path, object);
          var index2 = 0, length = path.length;
          while (object != null && index2 < length) {
            object = object[toKey(path[index2++])];
          }
          return index2 && index2 == length ? object : undefined$1;
        }
        function baseGetAllKeys(object, keysFunc, symbolsFunc) {
          var result2 = keysFunc(object);
          return isArray(object) ? result2 : arrayPush(result2, symbolsFunc(object));
        }
        function baseGetTag(value) {
          if (value == null) {
            return value === undefined$1 ? undefinedTag : nullTag;
          }
          return symToStringTag && symToStringTag in Object2(value) ? getRawTag(value) : objectToString(value);
        }
        function baseGt(value, other) {
          return value > other;
        }
        function baseHas(object, key) {
          return object != null && hasOwnProperty.call(object, key);
        }
        function baseHasIn(object, key) {
          return object != null && key in Object2(object);
        }
        function baseInRange(number, start, end) {
          return number >= nativeMin(start, end) && number < nativeMax(start, end);
        }
        function baseIntersection(arrays, iteratee2, comparator) {
          var includes2 = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array2(othLength), maxLength = Infinity, result2 = [];
          while (othIndex--) {
            var array = arrays[othIndex];
            if (othIndex && iteratee2) {
              array = arrayMap(array, baseUnary(iteratee2));
            }
            maxLength = nativeMin(array.length, maxLength);
            caches[othIndex] = !comparator && (iteratee2 || length >= 120 && array.length >= 120) ? new SetCache(othIndex && array) : undefined$1;
          }
          array = arrays[0];
          var index2 = -1, seen = caches[0];
          outer:
            while (++index2 < length && result2.length < maxLength) {
              var value = array[index2], computed = iteratee2 ? iteratee2(value) : value;
              value = comparator || value !== 0 ? value : 0;
              if (!(seen ? cacheHas(seen, computed) : includes2(result2, computed, comparator))) {
                othIndex = othLength;
                while (--othIndex) {
                  var cache = caches[othIndex];
                  if (!(cache ? cacheHas(cache, computed) : includes2(arrays[othIndex], computed, comparator))) {
                    continue outer;
                  }
                }
                if (seen) {
                  seen.push(computed);
                }
                result2.push(value);
              }
            }
          return result2;
        }
        function baseInverter(object, setter, iteratee2, accumulator) {
          baseForOwn(object, function(value, key, object2) {
            setter(accumulator, iteratee2(value), key, object2);
          });
          return accumulator;
        }
        function baseInvoke(object, path, args) {
          path = castPath(path, object);
          object = parent(object, path);
          var func = object == null ? object : object[toKey(last(path))];
          return func == null ? undefined$1 : apply(func, object, args);
        }
        function baseIsArguments(value) {
          return isObjectLike(value) && baseGetTag(value) == argsTag;
        }
        function baseIsArrayBuffer(value) {
          return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;
        }
        function baseIsDate(value) {
          return isObjectLike(value) && baseGetTag(value) == dateTag;
        }
        function baseIsEqual(value, other, bitmask, customizer, stack) {
          if (value === other) {
            return true;
          }
          if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) {
            return value !== value && other !== other;
          }
          return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
        }
        function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
          var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other);
          objTag = objTag == argsTag ? objectTag : objTag;
          othTag = othTag == argsTag ? objectTag : othTag;
          var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag;
          if (isSameTag && isBuffer(object)) {
            if (!isBuffer(other)) {
              return false;
            }
            objIsArr = true;
            objIsObj = false;
          }
          if (isSameTag && !objIsObj) {
            stack || (stack = new Stack());
            return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
          }
          if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
            var objIsWrapped = objIsObj && hasOwnProperty.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty.call(other, "__wrapped__");
            if (objIsWrapped || othIsWrapped) {
              var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
              stack || (stack = new Stack());
              return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
            }
          }
          if (!isSameTag) {
            return false;
          }
          stack || (stack = new Stack());
          return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
        }
        function baseIsMap(value) {
          return isObjectLike(value) && getTag(value) == mapTag;
        }
        function baseIsMatch(object, source, matchData, customizer) {
          var index2 = matchData.length, length = index2, noCustomizer = !customizer;
          if (object == null) {
            return !length;
          }
          object = Object2(object);
          while (index2--) {
            var data = matchData[index2];
            if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) {
              return false;
            }
          }
          while (++index2 < length) {
            data = matchData[index2];
            var key = data[0], objValue = object[key], srcValue = data[1];
            if (noCustomizer && data[2]) {
              if (objValue === undefined$1 && !(key in object)) {
                return false;
              }
            } else {
              var stack = new Stack();
              if (customizer) {
                var result2 = customizer(objValue, srcValue, key, object, source, stack);
              }
              if (!(result2 === undefined$1 ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result2)) {
                return false;
              }
            }
          }
          return true;
        }
        function baseIsNative(value) {
          if (!isObject2(value) || isMasked(value)) {
            return false;
          }
          var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
          return pattern.test(toSource(value));
        }
        function baseIsRegExp(value) {
          return isObjectLike(value) && baseGetTag(value) == regexpTag;
        }
        function baseIsSet(value) {
          return isObjectLike(value) && getTag(value) == setTag;
        }
        function baseIsTypedArray(value) {
          return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
        }
        function baseIteratee(value) {
          if (typeof value == "function") {
            return value;
          }
          if (value == null) {
            return identity;
          }
          if (typeof value == "object") {
            return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value);
          }
          return property(value);
        }
        function baseKeys(object) {
          if (!isPrototype(object)) {
            return nativeKeys(object);
          }
          var result2 = [];
          for (var key in Object2(object)) {
            if (hasOwnProperty.call(object, key) && key != "constructor") {
              result2.push(key);
            }
          }
          return result2;
        }
        function baseKeysIn(object) {
          if (!isObject2(object)) {
            return nativeKeysIn(object);
          }
          var isProto = isPrototype(object), result2 = [];
          for (var key in object) {
            if (!(key == "constructor" && (isProto || !hasOwnProperty.call(object, key)))) {
              result2.push(key);
            }
          }
          return result2;
        }
        function baseLt(value, other) {
          return value < other;
        }
        function baseMap(collection, iteratee2) {
          var index2 = -1, result2 = isArrayLike(collection) ? Array2(collection.length) : [];
          baseEach(collection, function(value, key, collection2) {
            result2[++index2] = iteratee2(value, key, collection2);
          });
          return result2;
        }
        function baseMatches(source) {
          var matchData = getMatchData(source);
          if (matchData.length == 1 && matchData[0][2]) {
            return matchesStrictComparable(matchData[0][0], matchData[0][1]);
          }
          return function(object) {
            return object === source || baseIsMatch(object, source, matchData);
          };
        }
        function baseMatchesProperty(path, srcValue) {
          if (isKey(path) && isStrictComparable(srcValue)) {
            return matchesStrictComparable(toKey(path), srcValue);
          }
          return function(object) {
            var objValue = get2(object, path);
            return objValue === undefined$1 && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
          };
        }
        function baseMerge(object, source, srcIndex, customizer, stack) {
          if (object === source) {
            return;
          }
          baseFor(source, function(srcValue, key) {
            stack || (stack = new Stack());
            if (isObject2(srcValue)) {
              baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
            } else {
              var newValue = customizer ? customizer(safeGet2(object, key), srcValue, key + "", object, source, stack) : undefined$1;
              if (newValue === undefined$1) {
                newValue = srcValue;
              }
              assignMergeValue(object, key, newValue);
            }
          }, keysIn);
        }
        function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
          var objValue = safeGet2(object, key), srcValue = safeGet2(source, key), stacked = stack.get(srcValue);
          if (stacked) {
            assignMergeValue(object, key, stacked);
            return;
          }
          var newValue = customizer ? customizer(objValue, srcValue, key + "", object, source, stack) : undefined$1;
          var isCommon = newValue === undefined$1;
          if (isCommon) {
            var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue);
            newValue = srcValue;
            if (isArr || isBuff || isTyped) {
              if (isArray(objValue)) {
                newValue = objValue;
              } else if (isArrayLikeObject(objValue)) {
                newValue = copyArray(objValue);
              } else if (isBuff) {
                isCommon = false;
                newValue = cloneBuffer(srcValue, true);
              } else if (isTyped) {
                isCommon = false;
                newValue = cloneTypedArray(srcValue, true);
              } else {
                newValue = [];
              }
            } else if (isPlainObject(srcValue) || isArguments(srcValue)) {
              newValue = objValue;
              if (isArguments(objValue)) {
                newValue = toPlainObject(objValue);
              } else if (!isObject2(objValue) || isFunction(objValue)) {
                newValue = initCloneObject(srcValue);
              }
            } else {
              isCommon = false;
            }
          }
          if (isCommon) {
            stack.set(srcValue, newValue);
            mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
            stack["delete"](srcValue);
          }
          assignMergeValue(object, key, newValue);
        }
        function baseNth(array, n2) {
          var length = array.length;
          if (!length) {
            return;
          }
          n2 += n2 < 0 ? length : 0;
          return isIndex(n2, length) ? array[n2] : undefined$1;
        }
        function baseOrderBy(collection, iteratees, orders) {
          if (iteratees.length) {
            iteratees = arrayMap(iteratees, function(iteratee2) {
              if (isArray(iteratee2)) {
                return function(value) {
                  return baseGet(value, iteratee2.length === 1 ? iteratee2[0] : iteratee2);
                };
              }
              return iteratee2;
            });
          } else {
            iteratees = [identity];
          }
          var index2 = -1;
          iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
          var result2 = baseMap(collection, function(value, key, collection2) {
            var criteria = arrayMap(iteratees, function(iteratee2) {
              return iteratee2(value);
            });
            return { "criteria": criteria, "index": ++index2, "value": value };
          });
          return baseSortBy(result2, function(object, other) {
            return compareMultiple(object, other, orders);
          });
        }
        function basePick(object, paths) {
          return basePickBy(object, paths, function(value, path) {
            return hasIn(object, path);
          });
        }
        function basePickBy(object, paths, predicate) {
          var index2 = -1, length = paths.length, result2 = {};
          while (++index2 < length) {
            var path = paths[index2], value = baseGet(object, path);
            if (predicate(value, path)) {
              baseSet(result2, castPath(path, object), value);
            }
          }
          return result2;
        }
        function basePropertyDeep(path) {
          return function(object) {
            return baseGet(object, path);
          };
        }
        function basePullAll(array, values2, iteratee2, comparator) {
          var indexOf2 = comparator ? baseIndexOfWith : baseIndexOf, index2 = -1, length = values2.length, seen = array;
          if (array === values2) {
            values2 = copyArray(values2);
          }
          if (iteratee2) {
            seen = arrayMap(array, baseUnary(iteratee2));
          }
          while (++index2 < length) {
            var fromIndex = 0, value = values2[index2], computed = iteratee2 ? iteratee2(value) : value;
            while ((fromIndex = indexOf2(seen, computed, fromIndex, comparator)) > -1) {
              if (seen !== array) {
                splice.call(seen, fromIndex, 1);
              }
              splice.call(array, fromIndex, 1);
            }
          }
          return array;
        }
        function basePullAt(array, indexes) {
          var length = array ? indexes.length : 0, lastIndex = length - 1;
          while (length--) {
            var index2 = indexes[length];
            if (length == lastIndex || index2 !== previous) {
              var previous = index2;
              if (isIndex(index2)) {
                splice.call(array, index2, 1);
              } else {
                baseUnset(array, index2);
              }
            }
          }
          return array;
        }
        function baseRandom(lower, upper) {
          return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
        }
        function baseRange(start, end, step, fromRight) {
          var index2 = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result2 = Array2(length);
          while (length--) {
            result2[fromRight ? length : ++index2] = start;
            start += step;
          }
          return result2;
        }
        function baseRepeat(string, n2) {
          var result2 = "";
          if (!string || n2 < 1 || n2 > MAX_SAFE_INTEGER) {
            return result2;
          }
          do {
            if (n2 % 2) {
              result2 += string;
            }
            n2 = nativeFloor(n2 / 2);
            if (n2) {
              string += string;
            }
          } while (n2);
          return result2;
        }
        function baseRest(func, start) {
          return setToString(overRest(func, start, identity), func + "");
        }
        function baseSample(collection) {
          return arraySample(values(collection));
        }
        function baseSampleSize(collection, n2) {
          var array = values(collection);
          return shuffleSelf(array, baseClamp(n2, 0, array.length));
        }
        function baseSet(object, path, value, customizer) {
          if (!isObject2(object)) {
            return object;
          }
          path = castPath(path, object);
          var index2 = -1, length = path.length, lastIndex = length - 1, nested = object;
          while (nested != null && ++index2 < length) {
            var key = toKey(path[index2]), newValue = value;
            if (key === "__proto__" || key === "constructor" || key === "prototype") {
              return object;
            }
            if (index2 != lastIndex) {
              var objValue = nested[key];
              newValue = customizer ? customizer(objValue, key, nested) : undefined$1;
              if (newValue === undefined$1) {
                newValue = isObject2(objValue) ? objValue : isIndex(path[index2 + 1]) ? [] : {};
              }
            }
            assignValue(nested, key, newValue);
            nested = nested[key];
          }
          return object;
        }
        var baseSetData = !metaMap ? identity : function(func, data) {
          metaMap.set(func, data);
          return func;
        };
        var baseSetToString = !defineProperty ? identity : function(func, string) {
          return defineProperty(func, "toString", {
            "configurable": true,
            "enumerable": false,
            "value": constant(string),
            "writable": true
          });
        };
        function baseShuffle(collection) {
          return shuffleSelf(values(collection));
        }
        function baseSlice(array, start, end) {
          var index2 = -1, length = array.length;
          if (start < 0) {
            start = -start > length ? 0 : length + start;
          }
          end = end > length ? length : end;
          if (end < 0) {
            end += length;
          }
          length = start > end ? 0 : end - start >>> 0;
          start >>>= 0;
          var result2 = Array2(length);
          while (++index2 < length) {
            result2[index2] = array[index2 + start];
          }
          return result2;
        }
        function baseSome(collection, predicate) {
          var result2;
          baseEach(collection, function(value, index2, collection2) {
            result2 = predicate(value, index2, collection2);
            return !result2;
          });
          return !!result2;
        }
        function baseSortedIndex(array, value, retHighest) {
          var low = 0, high = array == null ? low : array.length;
          if (typeof value == "number" && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
            while (low < high) {
              var mid = low + high >>> 1, computed = array[mid];
              if (computed !== null && !isSymbol(computed) && (retHighest ? computed <= value : computed < value)) {
                low = mid + 1;
              } else {
                high = mid;
              }
            }
            return high;
          }
          return baseSortedIndexBy(array, value, identity, retHighest);
        }
        function baseSortedIndexBy(array, value, iteratee2, retHighest) {
          var low = 0, high = array == null ? 0 : array.length;
          if (high === 0) {
            return 0;
          }
          value = iteratee2(value);
          var valIsNaN = value !== value, valIsNull = value === null, valIsSymbol = isSymbol(value), valIsUndefined = value === undefined$1;
          while (low < high) {
            var mid = nativeFloor((low + high) / 2), computed = iteratee2(array[mid]), othIsDefined = computed !== undefined$1, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol(computed);
            if (valIsNaN) {
              var setLow = retHighest || othIsReflexive;
            } else if (valIsUndefined) {
              setLow = othIsReflexive && (retHighest || othIsDefined);
            } else if (valIsNull) {
              setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
            } else if (valIsSymbol) {
              setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
            } else if (othIsNull || othIsSymbol) {
              setLow = false;
            } else {
              setLow = retHighest ? computed <= value : computed < value;
            }
            if (setLow) {
              low = mid + 1;
            } else {
              high = mid;
            }
          }
          return nativeMin(high, MAX_ARRAY_INDEX);
        }
        function baseSortedUniq(array, iteratee2) {
          var index2 = -1, length = array.length, resIndex = 0, result2 = [];
          while (++index2 < length) {
            var value = array[index2], computed = iteratee2 ? iteratee2(value) : value;
            if (!index2 || !eq(computed, seen)) {
              var seen = computed;
              result2[resIndex++] = value === 0 ? 0 : value;
            }
          }
          return result2;
        }
        function baseToNumber(value) {
          if (typeof value == "number") {
            return value;
          }
          if (isSymbol(value)) {
            return NAN;
          }
          return +value;
        }
        function baseToString(value) {
          if (typeof value == "string") {
            return value;
          }
          if (isArray(value)) {
            return arrayMap(value, baseToString) + "";
          }
          if (isSymbol(value)) {
            return symbolToString ? symbolToString.call(value) : "";
          }
          var result2 = value + "";
          return result2 == "0" && 1 / value == -INFINITY ? "-0" : result2;
        }
        function baseUniq(array, iteratee2, comparator) {
          var index2 = -1, includes2 = arrayIncludes, length = array.length, isCommon = true, result2 = [], seen = result2;
          if (comparator) {
            isCommon = false;
            includes2 = arrayIncludesWith;
          } else if (length >= LARGE_ARRAY_SIZE) {
            var set3 = iteratee2 ? null : createSet(array);
            if (set3) {
              return setToArray(set3);
            }
            isCommon = false;
            includes2 = cacheHas;
            seen = new SetCache();
          } else {
            seen = iteratee2 ? [] : result2;
          }
          outer:
            while (++index2 < length) {
              var value = array[index2], computed = iteratee2 ? iteratee2(value) : value;
              value = comparator || value !== 0 ? value : 0;
              if (isCommon && computed === computed) {
                var seenIndex = seen.length;
                while (seenIndex--) {
                  if (seen[seenIndex] === computed) {
                    continue outer;
                  }
                }
                if (iteratee2) {
                  seen.push(computed);
                }
                result2.push(value);
              } else if (!includes2(seen, computed, comparator)) {
                if (seen !== result2) {
                  seen.push(computed);
                }
                result2.push(value);
              }
            }
          return result2;
        }
        function baseUnset(object, path) {
          path = castPath(path, object);
          object = parent(object, path);
          return object == null || delete object[toKey(last(path))];
        }
        function baseUpdate(object, path, updater, customizer) {
          return baseSet(object, path, updater(baseGet(object, path)), customizer);
        }
        function baseWhile(array, predicate, isDrop, fromRight) {
          var length = array.length, index2 = fromRight ? length : -1;
          while ((fromRight ? index2-- : ++index2 < length) && predicate(array[index2], index2, array)) {
          }
          return isDrop ? baseSlice(array, fromRight ? 0 : index2, fromRight ? index2 + 1 : length) : baseSlice(array, fromRight ? index2 + 1 : 0, fromRight ? length : index2);
        }
        function baseWrapperValue(value, actions) {
          var result2 = value;
          if (result2 instanceof LazyWrapper) {
            result2 = result2.value();
          }
          return arrayReduce(actions, function(result3, action) {
            return action.func.apply(action.thisArg, arrayPush([result3], action.args));
          }, result2);
        }
        function baseXor(arrays, iteratee2, comparator) {
          var length = arrays.length;
          if (length < 2) {
            return length ? baseUniq(arrays[0]) : [];
          }
          var index2 = -1, result2 = Array2(length);
          while (++index2 < length) {
            var array = arrays[index2], othIndex = -1;
            while (++othIndex < length) {
              if (othIndex != index2) {
                result2[index2] = baseDifference(result2[index2] || array, arrays[othIndex], iteratee2, comparator);
              }
            }
          }
          return baseUniq(baseFlatten(result2, 1), iteratee2, comparator);
        }
        function baseZipObject(props, values2, assignFunc) {
          var index2 = -1, length = props.length, valsLength = values2.length, result2 = {};
          while (++index2 < length) {
            var value = index2 < valsLength ? values2[index2] : undefined$1;
            assignFunc(result2, props[index2], value);
          }
          return result2;
        }
        function castArrayLikeObject(value) {
          return isArrayLikeObject(value) ? value : [];
        }
        function castFunction(value) {
          return typeof value == "function" ? value : identity;
        }
        function castPath(value, object) {
          if (isArray(value)) {
            return value;
          }
          return isKey(value, object) ? [value] : stringToPath(toString(value));
        }
        var castRest = baseRest;
        function castSlice(array, start, end) {
          var length = array.length;
          end = end === undefined$1 ? length : end;
          return !start && end >= length ? array : baseSlice(array, start, end);
        }
        var clearTimeout2 = ctxClearTimeout || function(id) {
          return root.clearTimeout(id);
        };
        function cloneBuffer(buffer, isDeep) {
          if (isDeep) {
            return buffer.slice();
          }
          var length = buffer.length, result2 = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
          buffer.copy(result2);
          return result2;
        }
        function cloneArrayBuffer(arrayBuffer) {
          var result2 = new arrayBuffer.constructor(arrayBuffer.byteLength);
          new Uint8Array2(result2).set(new Uint8Array2(arrayBuffer));
          return result2;
        }
        function cloneDataView(dataView, isDeep) {
          var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
          return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
        }
        function cloneRegExp(regexp) {
          var result2 = new regexp.constructor(regexp.source, reFlags.exec(regexp));
          result2.lastIndex = regexp.lastIndex;
          return result2;
        }
        function cloneSymbol(symbol) {
          return symbolValueOf ? Object2(symbolValueOf.call(symbol)) : {};
        }
        function cloneTypedArray(typedArray, isDeep) {
          var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
          return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
        }
        function compareAscending(value, other) {
          if (value !== other) {
            var valIsDefined = value !== undefined$1, valIsNull = value === null, valIsReflexive = value === value, valIsSymbol = isSymbol(value);
            var othIsDefined = other !== undefined$1, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol(other);
            if (!othIsNull && !othIsSymbol && !valIsSymbol && value > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) {
              return 1;
            }
            if (!valIsNull && !valIsSymbol && !othIsSymbol && value < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) {
              return -1;
            }
          }
          return 0;
        }
        function compareMultiple(object, other, orders) {
          var index2 = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length;
          while (++index2 < length) {
            var result2 = compareAscending(objCriteria[index2], othCriteria[index2]);
            if (result2) {
              if (index2 >= ordersLength) {
                return result2;
              }
              var order = orders[index2];
              return result2 * (order == "desc" ? -1 : 1);
            }
          }
          return object.index - other.index;
        }
        function composeArgs(args, partials, holders, isCurried) {
          var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result2 = Array2(leftLength + rangeLength), isUncurried = !isCurried;
          while (++leftIndex < leftLength) {
            result2[leftIndex] = partials[leftIndex];
          }
          while (++argsIndex < holdersLength) {
            if (isUncurried || argsIndex < argsLength) {
              result2[holders[argsIndex]] = args[argsIndex];
            }
          }
          while (rangeLength--) {
            result2[leftIndex++] = args[argsIndex++];
          }
          return result2;
        }
        function composeArgsRight(args, partials, holders, isCurried) {
          var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result2 = Array2(rangeLength + rightLength), isUncurried = !isCurried;
          while (++argsIndex < rangeLength) {
            result2[argsIndex] = args[argsIndex];
          }
          var offset = argsIndex;
          while (++rightIndex < rightLength) {
            result2[offset + rightIndex] = partials[rightIndex];
          }
          while (++holdersIndex < holdersLength) {
            if (isUncurried || argsIndex < argsLength) {
              result2[offset + holders[holdersIndex]] = args[argsIndex++];
            }
          }
          return result2;
        }
        function copyArray(source, array) {
          var index2 = -1, length = source.length;
          array || (array = Array2(length));
          while (++index2 < length) {
            array[index2] = source[index2];
          }
          return array;
        }
        function copyObject(source, props, object, customizer) {
          var isNew = !object;
          object || (object = {});
          var index2 = -1, length = props.length;
          while (++index2 < length) {
            var key = props[index2];
            var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined$1;
            if (newValue === undefined$1) {
              newValue = source[key];
            }
            if (isNew) {
              baseAssignValue(object, key, newValue);
            } else {
              assignValue(object, key, newValue);
            }
          }
          return object;
        }
        function copySymbols(source, object) {
          return copyObject(source, getSymbols(source), object);
        }
        function copySymbolsIn(source, object) {
          return copyObject(source, getSymbolsIn(source), object);
        }
        function createAggregator(setter, initializer) {
          return function(collection, iteratee2) {
            var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {};
            return func(collection, setter, getIteratee(iteratee2, 2), accumulator);
          };
        }
        function createAssigner(assigner) {
          return baseRest(function(object, sources) {
            var index2 = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined$1, guard = length > 2 ? sources[2] : undefined$1;
            customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : undefined$1;
            if (guard && isIterateeCall(sources[0], sources[1], guard)) {
              customizer = length < 3 ? undefined$1 : customizer;
              length = 1;
            }
            object = Object2(object);
            while (++index2 < length) {
              var source = sources[index2];
              if (source) {
                assigner(object, source, index2, customizer);
              }
            }
            return object;
          });
        }
        function createBaseEach(eachFunc, fromRight) {
          return function(collection, iteratee2) {
            if (collection == null) {
              return collection;
            }
            if (!isArrayLike(collection)) {
              return eachFunc(collection, iteratee2);
            }
            var length = collection.length, index2 = fromRight ? length : -1, iterable = Object2(collection);
            while (fromRight ? index2-- : ++index2 < length) {
              if (iteratee2(iterable[index2], index2, iterable) === false) {
                break;
              }
            }
            return collection;
          };
        }
        function createBaseFor(fromRight) {
          return function(object, iteratee2, keysFunc) {
            var index2 = -1, iterable = Object2(object), props = keysFunc(object), length = props.length;
            while (length--) {
              var key = props[fromRight ? length : ++index2];
              if (iteratee2(iterable[key], key, iterable) === false) {
                break;
              }
            }
            return object;
          };
        }
        function createBind(func, bitmask, thisArg) {
          var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func);
          function wrapper() {
            var fn2 = this && this !== root && this instanceof wrapper ? Ctor : func;
            return fn2.apply(isBind ? thisArg : this, arguments);
          }
          return wrapper;
        }
        function createCaseFirst(methodName) {
          return function(string) {
            string = toString(string);
            var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined$1;
            var chr = strSymbols ? strSymbols[0] : string.charAt(0);
            var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string.slice(1);
            return chr[methodName]() + trailing;
          };
        }
        function createCompounder(callback) {
          return function(string) {
            return arrayReduce(words(deburr(string).replace(reApos, "")), callback, "");
          };
        }
        function createCtor(Ctor) {
          return function() {
            var args = arguments;
            switch (args.length) {
              case 0:
                return new Ctor();
              case 1:
                return new Ctor(args[0]);
              case 2:
                return new Ctor(args[0], args[1]);
              case 3:
                return new Ctor(args[0], args[1], args[2]);
              case 4:
                return new Ctor(args[0], args[1], args[2], args[3]);
              case 5:
                return new Ctor(args[0], args[1], args[2], args[3], args[4]);
              case 6:
                return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
              case 7:
                return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
            }
            var thisBinding = baseCreate(Ctor.prototype), result2 = Ctor.apply(thisBinding, args);
            return isObject2(result2) ? result2 : thisBinding;
          };
        }
        function createCurry(func, bitmask, arity) {
          var Ctor = createCtor(func);
          function wrapper() {
            var length = arguments.length, args = Array2(length), index2 = length, placeholder = getHolder(wrapper);
            while (index2--) {
              args[index2] = arguments[index2];
            }
            var holders = length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder ? [] : replaceHolders(args, placeholder);
            length -= holders.length;
            if (length < arity) {
              return createRecurry(
                func,
                bitmask,
                createHybrid,
                wrapper.placeholder,
                undefined$1,
                args,
                holders,
                undefined$1,
                undefined$1,
                arity - length
              );
            }
            var fn2 = this && this !== root && this instanceof wrapper ? Ctor : func;
            return apply(fn2, this, args);
          }
          return wrapper;
        }
        function createFind(findIndexFunc) {
          return function(collection, predicate, fromIndex) {
            var iterable = Object2(collection);
            if (!isArrayLike(collection)) {
              var iteratee2 = getIteratee(predicate, 3);
              collection = keys(collection);
              predicate = function(key) {
                return iteratee2(iterable[key], key, iterable);
              };
            }
            var index2 = findIndexFunc(collection, predicate, fromIndex);
            return index2 > -1 ? iterable[iteratee2 ? collection[index2] : index2] : undefined$1;
          };
        }
        function createFlow(fromRight) {
          return flatRest(function(funcs) {
            var length = funcs.length, index2 = length, prereq = LodashWrapper.prototype.thru;
            if (fromRight) {
              funcs.reverse();
            }
            while (index2--) {
              var func = funcs[index2];
              if (typeof func != "function") {
                throw new TypeError2(FUNC_ERROR_TEXT);
              }
              if (prereq && !wrapper && getFuncName(func) == "wrapper") {
                var wrapper = new LodashWrapper([], true);
              }
            }
            index2 = wrapper ? index2 : length;
            while (++index2 < length) {
              func = funcs[index2];
              var funcName = getFuncName(func), data = funcName == "wrapper" ? getData(func) : undefined$1;
              if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1) {
                wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
              } else {
                wrapper = func.length == 1 && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func);
              }
            }
            return function() {
              var args = arguments, value = args[0];
              if (wrapper && args.length == 1 && isArray(value)) {
                return wrapper.plant(value).value();
              }
              var index3 = 0, result2 = length ? funcs[index3].apply(this, args) : value;
              while (++index3 < length) {
                result2 = funcs[index3].call(this, result2);
              }
              return result2;
            };
          });
        }
        function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary2, arity) {
          var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined$1 : createCtor(func);
          function wrapper() {
            var length = arguments.length, args = Array2(length), index2 = length;
            while (index2--) {
              args[index2] = arguments[index2];
            }
            if (isCurried) {
              var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder);
            }
            if (partials) {
              args = composeArgs(args, partials, holders, isCurried);
            }
            if (partialsRight) {
              args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
            }
            length -= holdersCount;
            if (isCurried && length < arity) {
              var newHolders = replaceHolders(args, placeholder);
              return createRecurry(
                func,
                bitmask,
                createHybrid,
                wrapper.placeholder,
                thisArg,
                args,
                newHolders,
                argPos,
                ary2,
                arity - length
              );
            }
            var thisBinding = isBind ? thisArg : this, fn2 = isBindKey ? thisBinding[func] : func;
            length = args.length;
            if (argPos) {
              args = reorder(args, argPos);
            } else if (isFlip && length > 1) {
              args.reverse();
            }
            if (isAry && ary2 < length) {
              args.length = ary2;
            }
            if (this && this !== root && this instanceof wrapper) {
              fn2 = Ctor || createCtor(fn2);
            }
            return fn2.apply(thisBinding, args);
          }
          return wrapper;
        }
        function createInverter(setter, toIteratee) {
          return function(object, iteratee2) {
            return baseInverter(object, setter, toIteratee(iteratee2), {});
          };
        }
        function createMathOperation(operator, defaultValue2) {
          return function(value, other) {
            var result2;
            if (value === undefined$1 && other === undefined$1) {
              return defaultValue2;
            }
            if (value !== undefined$1) {
              result2 = value;
            }
            if (other !== undefined$1) {
              if (result2 === undefined$1) {
                return other;
              }
              if (typeof value == "string" || typeof other == "string") {
                value = baseToString(value);
                other = baseToString(other);
              } else {
                value = baseToNumber(value);
                other = baseToNumber(other);
              }
              result2 = operator(value, other);
            }
            return result2;
          };
        }
        function createOver(arrayFunc) {
          return flatRest(function(iteratees) {
            iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
            return baseRest(function(args) {
              var thisArg = this;
              return arrayFunc(iteratees, function(iteratee2) {
                return apply(iteratee2, thisArg, args);
              });
            });
          });
        }
        function createPadding(length, chars2) {
          chars2 = chars2 === undefined$1 ? " " : baseToString(chars2);
          var charsLength = chars2.length;
          if (charsLength < 2) {
            return charsLength ? baseRepeat(chars2, length) : chars2;
          }
          var result2 = baseRepeat(chars2, nativeCeil(length / stringSize(chars2)));
          return hasUnicode(chars2) ? castSlice(stringToArray(result2), 0, length).join("") : result2.slice(0, length);
        }
        function createPartial(func, bitmask, thisArg, partials) {
          var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func);
          function wrapper() {
            var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array2(leftLength + argsLength), fn2 = this && this !== root && this instanceof wrapper ? Ctor : func;
            while (++leftIndex < leftLength) {
              args[leftIndex] = partials[leftIndex];
            }
            while (argsLength--) {
              args[leftIndex++] = arguments[++argsIndex];
            }
            return apply(fn2, isBind ? thisArg : this, args);
          }
          return wrapper;
        }
        function createRange(fromRight) {
          return function(start, end, step) {
            if (step && typeof step != "number" && isIterateeCall(start, end, step)) {
              end = step = undefined$1;
            }
            start = toFinite(start);
            if (end === undefined$1) {
              end = start;
              start = 0;
            } else {
              end = toFinite(end);
            }
            step = step === undefined$1 ? start < end ? 1 : -1 : toFinite(step);
            return baseRange(start, end, step, fromRight);
          };
        }
        function createRelationalOperation(operator) {
          return function(value, other) {
            if (!(typeof value == "string" && typeof other == "string")) {
              value = toNumber(value);
              other = toNumber(other);
            }
            return operator(value, other);
          };
        }
        function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary2, arity) {
          var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined$1, newHoldersRight = isCurry ? undefined$1 : holders, newPartials = isCurry ? partials : undefined$1, newPartialsRight = isCurry ? undefined$1 : partials;
          bitmask |= isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG;
          bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
          if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
            bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
          }
          var newData = [
            func,
            bitmask,
            thisArg,
            newPartials,
            newHolders,
            newPartialsRight,
            newHoldersRight,
            argPos,
            ary2,
            arity
          ];
          var result2 = wrapFunc.apply(undefined$1, newData);
          if (isLaziable(func)) {
            setData(result2, newData);
          }
          result2.placeholder = placeholder;
          return setWrapToString(result2, func, bitmask);
        }
        function createRound(methodName) {
          var func = Math2[methodName];
          return function(number, precision) {
            number = toNumber(number);
            precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);
            if (precision && nativeIsFinite(number)) {
              var pair = (toString(number) + "e").split("e"), value = func(pair[0] + "e" + (+pair[1] + precision));
              pair = (toString(value) + "e").split("e");
              return +(pair[0] + "e" + (+pair[1] - precision));
            }
            return func(number);
          };
        }
        var createSet = !(Set2 && 1 / setToArray(new Set2([, -0]))[1] == INFINITY) ? noop2 : function(values2) {
          return new Set2(values2);
        };
        function createToPairs(keysFunc) {
          return function(object) {
            var tag = getTag(object);
            if (tag == mapTag) {
              return mapToArray(object);
            }
            if (tag == setTag) {
              return setToPairs(object);
            }
            return baseToPairs(object, keysFunc(object));
          };
        }
        function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary2, arity) {
          var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
          if (!isBindKey && typeof func != "function") {
            throw new TypeError2(FUNC_ERROR_TEXT);
          }
          var length = partials ? partials.length : 0;
          if (!length) {
            bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
            partials = holders = undefined$1;
          }
          ary2 = ary2 === undefined$1 ? ary2 : nativeMax(toInteger(ary2), 0);
          arity = arity === undefined$1 ? arity : toInteger(arity);
          length -= holders ? holders.length : 0;
          if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
            var partialsRight = partials, holdersRight = holders;
            partials = holders = undefined$1;
          }
          var data = isBindKey ? undefined$1 : getData(func);
          var newData = [
            func,
            bitmask,
            thisArg,
            partials,
            holders,
            partialsRight,
            holdersRight,
            argPos,
            ary2,
            arity
          ];
          if (data) {
            mergeData(newData, data);
          }
          func = newData[0];
          bitmask = newData[1];
          thisArg = newData[2];
          partials = newData[3];
          holders = newData[4];
          arity = newData[9] = newData[9] === undefined$1 ? isBindKey ? 0 : func.length : nativeMax(newData[9] - length, 0);
          if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
            bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
          }
          if (!bitmask || bitmask == WRAP_BIND_FLAG) {
            var result2 = createBind(func, bitmask, thisArg);
          } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
            result2 = createCurry(func, bitmask, arity);
          } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
            result2 = createPartial(func, bitmask, thisArg, partials);
          } else {
            result2 = createHybrid.apply(undefined$1, newData);
          }
          var setter = data ? baseSetData : setData;
          return setWrapToString(setter(result2, newData), func, bitmask);
        }
        function customDefaultsAssignIn(objValue, srcValue, key, object) {
          if (objValue === undefined$1 || eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key)) {
            return srcValue;
          }
          return objValue;
        }
        function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {
          if (isObject2(objValue) && isObject2(srcValue)) {
            stack.set(srcValue, objValue);
            baseMerge(objValue, srcValue, undefined$1, customDefaultsMerge, stack);
            stack["delete"](srcValue);
          }
          return objValue;
        }
        function customOmitClone(value) {
          return isPlainObject(value) ? undefined$1 : value;
        }
        function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
          var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length;
          if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
            return false;
          }
          var arrStacked = stack.get(array);
          var othStacked = stack.get(other);
          if (arrStacked && othStacked) {
            return arrStacked == other && othStacked == array;
          }
          var index2 = -1, result2 = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : undefined$1;
          stack.set(array, other);
          stack.set(other, array);
          while (++index2 < arrLength) {
            var arrValue = array[index2], othValue = other[index2];
            if (customizer) {
              var compared = isPartial ? customizer(othValue, arrValue, index2, other, array, stack) : customizer(arrValue, othValue, index2, array, other, stack);
            }
            if (compared !== undefined$1) {
              if (compared) {
                continue;
              }
              result2 = false;
              break;
            }
            if (seen) {
              if (!arraySome(other, function(othValue2, othIndex) {
                if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
                  return seen.push(othIndex);
                }
              })) {
                result2 = false;
                break;
              }
            } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
              result2 = false;
              break;
            }
          }
          stack["delete"](array);
          stack["delete"](other);
          return result2;
        }
        function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
          switch (tag) {
            case dataViewTag:
              if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
                return false;
              }
              object = object.buffer;
              other = other.buffer;
            case arrayBufferTag:
              if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) {
                return false;
              }
              return true;
            case boolTag:
            case dateTag:
            case numberTag:
              return eq(+object, +other);
            case errorTag:
              return object.name == other.name && object.message == other.message;
            case regexpTag:
            case stringTag:
              return object == other + "";
            case mapTag:
              var convert = mapToArray;
            case setTag:
              var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
              convert || (convert = setToArray);
              if (object.size != other.size && !isPartial) {
                return false;
              }
              var stacked = stack.get(object);
              if (stacked) {
                return stacked == other;
              }
              bitmask |= COMPARE_UNORDERED_FLAG;
              stack.set(object, other);
              var result2 = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
              stack["delete"](object);
              return result2;
            case symbolTag:
              if (symbolValueOf) {
                return symbolValueOf.call(object) == symbolValueOf.call(other);
              }
          }
          return false;
        }
        function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
          var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length;
          if (objLength != othLength && !isPartial) {
            return false;
          }
          var index2 = objLength;
          while (index2--) {
            var key = objProps[index2];
            if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
              return false;
            }
          }
          var objStacked = stack.get(object);
          var othStacked = stack.get(other);
          if (objStacked && othStacked) {
            return objStacked == other && othStacked == object;
          }
          var result2 = true;
          stack.set(object, other);
          stack.set(other, object);
          var skipCtor = isPartial;
          while (++index2 < objLength) {
            key = objProps[index2];
            var objValue = object[key], othValue = other[key];
            if (customizer) {
              var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
            }
            if (!(compared === undefined$1 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
              result2 = false;
              break;
            }
            skipCtor || (skipCtor = key == "constructor");
          }
          if (result2 && !skipCtor) {
            var objCtor = object.constructor, othCtor = other.constructor;
            if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
              result2 = false;
            }
          }
          stack["delete"](object);
          stack["delete"](other);
          return result2;
        }
        function flatRest(func) {
          return setToString(overRest(func, undefined$1, flatten), func + "");
        }
        function getAllKeys(object) {
          return baseGetAllKeys(object, keys, getSymbols);
        }
        function getAllKeysIn(object) {
          return baseGetAllKeys(object, keysIn, getSymbolsIn);
        }
        var getData = !metaMap ? noop2 : function(func) {
          return metaMap.get(func);
        };
        function getFuncName(func) {
          var result2 = func.name + "", array = realNames[result2], length = hasOwnProperty.call(realNames, result2) ? array.length : 0;
          while (length--) {
            var data = array[length], otherFunc = data.func;
            if (otherFunc == null || otherFunc == func) {
              return data.name;
            }
          }
          return result2;
        }
        function getHolder(func) {
          var object = hasOwnProperty.call(lodash2, "placeholder") ? lodash2 : func;
          return object.placeholder;
        }
        function getIteratee() {
          var result2 = lodash2.iteratee || iteratee;
          result2 = result2 === iteratee ? baseIteratee : result2;
          return arguments.length ? result2(arguments[0], arguments[1]) : result2;
        }
        function getMapData(map3, key) {
          var data = map3.__data__;
          return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
        }
        function getMatchData(object) {
          var result2 = keys(object), length = result2.length;
          while (length--) {
            var key = result2[length], value = object[key];
            result2[length] = [key, value, isStrictComparable(value)];
          }
          return result2;
        }
        function getNative(object, key) {
          var value = getValue(object, key);
          return baseIsNative(value) ? value : undefined$1;
        }
        function getRawTag(value) {
          var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag];
          try {
            value[symToStringTag] = undefined$1;
            var unmasked = true;
          } catch (e2) {
          }
          var result2 = nativeObjectToString.call(value);
          if (unmasked) {
            if (isOwn) {
              value[symToStringTag] = tag;
            } else {
              delete value[symToStringTag];
            }
          }
          return result2;
        }
        var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
          if (object == null) {
            return [];
          }
          object = Object2(object);
          return arrayFilter(nativeGetSymbols(object), function(symbol) {
            return propertyIsEnumerable.call(object, symbol);
          });
        };
        var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
          var result2 = [];
          while (object) {
            arrayPush(result2, getSymbols(object));
            object = getPrototype(object);
          }
          return result2;
        };
        var getTag = baseGetTag;
        if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap2 && getTag(new WeakMap2()) != weakMapTag) {
          getTag = function(value) {
            var result2 = baseGetTag(value), Ctor = result2 == objectTag ? value.constructor : undefined$1, ctorString = Ctor ? toSource(Ctor) : "";
            if (ctorString) {
              switch (ctorString) {
                case dataViewCtorString:
                  return dataViewTag;
                case mapCtorString:
                  return mapTag;
                case promiseCtorString:
                  return promiseTag;
                case setCtorString:
                  return setTag;
                case weakMapCtorString:
                  return weakMapTag;
              }
            }
            return result2;
          };
        }
        function getView(start, end, transforms) {
          var index2 = -1, length = transforms.length;
          while (++index2 < length) {
            var data = transforms[index2], size2 = data.size;
            switch (data.type) {
              case "drop":
                start += size2;
                break;
              case "dropRight":
                end -= size2;
                break;
              case "take":
                end = nativeMin(end, start + size2);
                break;
              case "takeRight":
                start = nativeMax(start, end - size2);
                break;
            }
          }
          return { "start": start, "end": end };
        }
        function getWrapDetails(source) {
          var match = source.match(reWrapDetails);
          return match ? match[1].split(reSplitDetails) : [];
        }
        function hasPath(object, path, hasFunc) {
          path = castPath(path, object);
          var index2 = -1, length = path.length, result2 = false;
          while (++index2 < length) {
            var key = toKey(path[index2]);
            if (!(result2 = object != null && hasFunc(object, key))) {
              break;
            }
            object = object[key];
          }
          if (result2 || ++index2 != length) {
            return result2;
          }
          length = object == null ? 0 : object.length;
          return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object));
        }
        function initCloneArray(array) {
          var length = array.length, result2 = new array.constructor(length);
          if (length && typeof array[0] == "string" && hasOwnProperty.call(array, "index")) {
            result2.index = array.index;
            result2.input = array.input;
          }
          return result2;
        }
        function initCloneObject(object) {
          return typeof object.constructor == "function" && !isPrototype(object) ? baseCreate(getPrototype(object)) : {};
        }
        function initCloneByTag(object, tag, isDeep) {
          var Ctor = object.constructor;
          switch (tag) {
            case arrayBufferTag:
              return cloneArrayBuffer(object);
            case boolTag:
            case dateTag:
              return new Ctor(+object);
            case dataViewTag:
              return cloneDataView(object, isDeep);
            case float32Tag:
            case float64Tag:
            case int8Tag:
            case int16Tag:
            case int32Tag:
            case uint8Tag:
            case uint8ClampedTag:
            case uint16Tag:
            case uint32Tag:
              return cloneTypedArray(object, isDeep);
            case mapTag:
              return new Ctor();
            case numberTag:
            case stringTag:
              return new Ctor(object);
            case regexpTag:
              return cloneRegExp(object);
            case setTag:
              return new Ctor();
            case symbolTag:
              return cloneSymbol(object);
          }
        }
        function insertWrapDetails(source, details) {
          var length = details.length;
          if (!length) {
            return source;
          }
          var lastIndex = length - 1;
          details[lastIndex] = (length > 1 ? "& " : "") + details[lastIndex];
          details = details.join(length > 2 ? ", " : " ");
          return source.replace(reWrapComment, "{\n/* [wrapped with " + details + "] */\n");
        }
        function isFlattenable(value) {
          return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]);
        }
        function isIndex(value, length) {
          var type = typeof value;
          length = length == null ? MAX_SAFE_INTEGER : length;
          return !!length && (type == "number" || type != "symbol" && reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
        }
        function isIterateeCall(value, index2, object) {
          if (!isObject2(object)) {
            return false;
          }
          var type = typeof index2;
          if (type == "number" ? isArrayLike(object) && isIndex(index2, object.length) : type == "string" && index2 in object) {
            return eq(object[index2], value);
          }
          return false;
        }
        function isKey(value, object) {
          if (isArray(value)) {
            return false;
          }
          var type = typeof value;
          if (type == "number" || type == "symbol" || type == "boolean" || value == null || isSymbol(value)) {
            return true;
          }
          return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || object != null && value in Object2(object);
        }
        function isKeyable(value) {
          var type = typeof value;
          return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
        }
        function isLaziable(func) {
          var funcName = getFuncName(func), other = lodash2[funcName];
          if (typeof other != "function" || !(funcName in LazyWrapper.prototype)) {
            return false;
          }
          if (func === other) {
            return true;
          }
          var data = getData(other);
          return !!data && func === data[0];
        }
        function isMasked(func) {
          return !!maskSrcKey && maskSrcKey in func;
        }
        var isMaskable = coreJsData ? isFunction : stubFalse;
        function isPrototype(value) {
          var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto;
          return value === proto;
        }
        function isStrictComparable(value) {
          return value === value && !isObject2(value);
        }
        function matchesStrictComparable(key, srcValue) {
          return function(object) {
            if (object == null) {
              return false;
            }
            return object[key] === srcValue && (srcValue !== undefined$1 || key in Object2(object));
          };
        }
        function memoizeCapped(func) {
          var result2 = memoize(func, function(key) {
            if (cache.size === MAX_MEMOIZE_SIZE) {
              cache.clear();
            }
            return key;
          });
          var cache = result2.cache;
          return result2;
        }
        function mergeData(data, source) {
          var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
          var isCombo = srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_CURRY_FLAG || srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_REARG_FLAG && data[7].length <= source[8] || srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG) && source[7].length <= source[8] && bitmask == WRAP_CURRY_FLAG;
          if (!(isCommon || isCombo)) {
            return data;
          }
          if (srcBitmask & WRAP_BIND_FLAG) {
            data[2] = source[2];
            newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
          }
          var value = source[3];
          if (value) {
            var partials = data[3];
            data[3] = partials ? composeArgs(partials, value, source[4]) : value;
            data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
          }
          value = source[5];
          if (value) {
            partials = data[5];
            data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
            data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
          }
          value = source[7];
          if (value) {
            data[7] = value;
          }
          if (srcBitmask & WRAP_ARY_FLAG) {
            data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
          }
          if (data[9] == null) {
            data[9] = source[9];
          }
          data[0] = source[0];
          data[1] = newBitmask;
          return data;
        }
        function nativeKeysIn(object) {
          var result2 = [];
          if (object != null) {
            for (var key in Object2(object)) {
              result2.push(key);
            }
          }
          return result2;
        }
        function objectToString(value) {
          return nativeObjectToString.call(value);
        }
        function overRest(func, start, transform2) {
          start = nativeMax(start === undefined$1 ? func.length - 1 : start, 0);
          return function() {
            var args = arguments, index2 = -1, length = nativeMax(args.length - start, 0), array = Array2(length);
            while (++index2 < length) {
              array[index2] = args[start + index2];
            }
            index2 = -1;
            var otherArgs = Array2(start + 1);
            while (++index2 < start) {
              otherArgs[index2] = args[index2];
            }
            otherArgs[start] = transform2(array);
            return apply(func, this, otherArgs);
          };
        }
        function parent(object, path) {
          return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
        }
        function reorder(array, indexes) {
          var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array);
          while (length--) {
            var index2 = indexes[length];
            array[length] = isIndex(index2, arrLength) ? oldArray[index2] : undefined$1;
          }
          return array;
        }
        function safeGet2(object, key) {
          if (key === "constructor" && typeof object[key] === "function") {
            return;
          }
          if (key == "__proto__") {
            return;
          }
          return object[key];
        }
        var setData = shortOut(baseSetData);
        var setTimeout2 = ctxSetTimeout || function(func, wait) {
          return root.setTimeout(func, wait);
        };
        var setToString = shortOut(baseSetToString);
        function setWrapToString(wrapper, reference, bitmask) {
          var source = reference + "";
          return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
        }
        function shortOut(func) {
          var count = 0, lastCalled = 0;
          return function() {
            var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled);
            lastCalled = stamp;
            if (remaining > 0) {
              if (++count >= HOT_COUNT) {
                return arguments[0];
              }
            } else {
              count = 0;
            }
            return func.apply(undefined$1, arguments);
          };
        }
        function shuffleSelf(array, size2) {
          var index2 = -1, length = array.length, lastIndex = length - 1;
          size2 = size2 === undefined$1 ? length : size2;
          while (++index2 < size2) {
            var rand = baseRandom(index2, lastIndex), value = array[rand];
            array[rand] = array[index2];
            array[index2] = value;
          }
          array.length = size2;
          return array;
        }
        var stringToPath = memoizeCapped(function(string) {
          var result2 = [];
          if (string.charCodeAt(0) === 46) {
            result2.push("");
          }
          string.replace(rePropName, function(match, number, quote, subString) {
            result2.push(quote ? subString.replace(reEscapeChar, "$1") : number || match);
          });
          return result2;
        });
        function toKey(value) {
          if (typeof value == "string" || isSymbol(value)) {
            return value;
          }
          var result2 = value + "";
          return result2 == "0" && 1 / value == -INFINITY ? "-0" : result2;
        }
        function toSource(func) {
          if (func != null) {
            try {
              return funcToString.call(func);
            } catch (e2) {
            }
            try {
              return func + "";
            } catch (e2) {
            }
          }
          return "";
        }
        function updateWrapDetails(details, bitmask) {
          arrayEach(wrapFlags, function(pair) {
            var value = "_." + pair[0];
            if (bitmask & pair[1] && !arrayIncludes(details, value)) {
              details.push(value);
            }
          });
          return details.sort();
        }
        function wrapperClone(wrapper) {
          if (wrapper instanceof LazyWrapper) {
            return wrapper.clone();
          }
          var result2 = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
          result2.__actions__ = copyArray(wrapper.__actions__);
          result2.__index__ = wrapper.__index__;
          result2.__values__ = wrapper.__values__;
          return result2;
        }
        function chunk(array, size2, guard) {
          if (guard ? isIterateeCall(array, size2, guard) : size2 === undefined$1) {
            size2 = 1;
          } else {
            size2 = nativeMax(toInteger(size2), 0);
          }
          var length = array == null ? 0 : array.length;
          if (!length || size2 < 1) {
            return [];
          }
          var index2 = 0, resIndex = 0, result2 = Array2(nativeCeil(length / size2));
          while (index2 < length) {
            result2[resIndex++] = baseSlice(array, index2, index2 += size2);
          }
          return result2;
        }
        function compact(array) {
          var index2 = -1, length = array == null ? 0 : array.length, resIndex = 0, result2 = [];
          while (++index2 < length) {
            var value = array[index2];
            if (value) {
              result2[resIndex++] = value;
            }
          }
          return result2;
        }
        function concat() {
          var length = arguments.length;
          if (!length) {
            return [];
          }
          var args = Array2(length - 1), array = arguments[0], index2 = length;
          while (index2--) {
            args[index2 - 1] = arguments[index2];
          }
          return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
        }
        var difference = baseRest(function(array, values2) {
          return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true)) : [];
        });
        var differenceBy = baseRest(function(array, values2) {
          var iteratee2 = last(values2);
          if (isArrayLikeObject(iteratee2)) {
            iteratee2 = undefined$1;
          }
          return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true), getIteratee(iteratee2, 2)) : [];
        });
        var differenceWith = baseRest(function(array, values2) {
          var comparator = last(values2);
          if (isArrayLikeObject(comparator)) {
            comparator = undefined$1;
          }
          return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true), undefined$1, comparator) : [];
        });
        function drop(array, n2, guard) {
          var length = array == null ? 0 : array.length;
          if (!length) {
            return [];
          }
          n2 = guard || n2 === undefined$1 ? 1 : toInteger(n2);
          return baseSlice(array, n2 < 0 ? 0 : n2, length);
        }
        function dropRight(array, n2, guard) {
          var length = array == null ? 0 : array.length;
          if (!length) {
            return [];
          }
          n2 = guard || n2 === undefined$1 ? 1 : toInteger(n2);
          n2 = length - n2;
          return baseSlice(array, 0, n2 < 0 ? 0 : n2);
        }
        function dropRightWhile(array, predicate) {
          return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true, true) : [];
        }
        function dropWhile(array, predicate) {
          return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true) : [];
        }
        function fill(array, value, start, end) {
          var length = array == null ? 0 : array.length;
          if (!length) {
            return [];
          }
          if (start && typeof start != "number" && isIterateeCall(array, value, start)) {
            start = 0;
            end = length;
          }
          return baseFill(array, value, start, end);
        }
        function findIndex(array, predicate, fromIndex) {
          var length = array == null ? 0 : array.length;
          if (!length) {
            return -1;
          }
          var index2 = fromIndex == null ? 0 : toInteger(fromIndex);
          if (index2 < 0) {
            index2 = nativeMax(length + index2, 0);
          }
          return baseFindIndex(array, getIteratee(predicate, 3), index2);
        }
        function findLastIndex(array, predicate, fromIndex) {
          var length = array == null ? 0 : array.length;
          if (!length) {
            return -1;
          }
          var index2 = length - 1;
          if (fromIndex !== undefined$1) {
            index2 = toInteger(fromIndex);
            index2 = fromIndex < 0 ? nativeMax(length + index2, 0) : nativeMin(index2, length - 1);
          }
          return baseFindIndex(array, getIteratee(predicate, 3), index2, true);
        }
        function flatten(array) {
          var length = array == null ? 0 : array.length;
          return length ? baseFlatten(array, 1) : [];
        }
        function flattenDeep(array) {
          var length = array == null ? 0 : array.length;
          return length ? baseFlatten(array, INFINITY) : [];
        }
        function flattenDepth(array, depth) {
          var length = array == null ? 0 : array.length;
          if (!length) {
            return [];
          }
          depth = depth === undefined$1 ? 1 : toInteger(depth);
          return baseFlatten(array, depth);
        }
        function fromPairs(pairs) {
          var index2 = -1, length = pairs == null ? 0 : pairs.length, result2 = {};
          while (++index2 < length) {
            var pair = pairs[index2];
            result2[pair[0]] = pair[1];
          }
          return result2;
        }
        function head(array) {
          return array && array.length ? array[0] : undefined$1;
        }
        function indexOf(array, value, fromIndex) {
          var length = array == null ? 0 : array.length;
          if (!length) {
            return -1;
          }
          var index2 = fromIndex == null ? 0 : toInteger(fromIndex);
          if (index2 < 0) {
            index2 = nativeMax(length + index2, 0);
          }
          return baseIndexOf(array, value, index2);
        }
        function initial(array) {
          var length = array == null ? 0 : array.length;
          return length ? baseSlice(array, 0, -1) : [];
        }
        var intersection = baseRest(function(arrays) {
          var mapped = arrayMap(arrays, castArrayLikeObject);
          return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped) : [];
        });
        var intersectionBy = baseRest(function(arrays) {
          var iteratee2 = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject);
          if (iteratee2 === last(mapped)) {
            iteratee2 = undefined$1;
          } else {
            mapped.pop();
          }
          return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, getIteratee(iteratee2, 2)) : [];
        });
        var intersectionWith = baseRest(function(arrays) {
          var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject);
          comparator = typeof comparator == "function" ? comparator : undefined$1;
          if (comparator) {
            mapped.pop();
          }
          return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, undefined$1, comparator) : [];
        });
        function join(array, separator) {
          return array == null ? "" : nativeJoin.call(array, separator);
        }
        function last(array) {
          var length = array == null ? 0 : array.length;
          return length ? array[length - 1] : undefined$1;
        }
        function lastIndexOf(array, value, fromIndex) {
          var length = array == null ? 0 : array.length;
          if (!length) {
            return -1;
          }
          var index2 = length;
          if (fromIndex !== undefined$1) {
            index2 = toInteger(fromIndex);
            index2 = index2 < 0 ? nativeMax(length + index2, 0) : nativeMin(index2, length - 1);
          }
          return value === value ? strictLastIndexOf(array, value, index2) : baseFindIndex(array, baseIsNaN, index2, true);
        }
        function nth(array, n2) {
          return array && array.length ? baseNth(array, toInteger(n2)) : undefined$1;
        }
        var pull = baseRest(pullAll);
        function pullAll(array, values2) {
          return array && array.length && values2 && values2.length ? basePullAll(array, values2) : array;
        }
        function pullAllBy(array, values2, iteratee2) {
          return array && array.length && values2 && values2.length ? basePullAll(array, values2, getIteratee(iteratee2, 2)) : array;
        }
        function pullAllWith(array, values2, comparator) {
          return array && array.length && values2 && values2.length ? basePullAll(array, values2, undefined$1, comparator) : array;
        }
        var pullAt = flatRest(function(array, indexes) {
          var length = array == null ? 0 : array.length, result2 = baseAt(array, indexes);
          basePullAt(array, arrayMap(indexes, function(index2) {
            return isIndex(index2, length) ? +index2 : index2;
          }).sort(compareAscending));
          return result2;
        });
        function remove(array, predicate) {
          var result2 = [];
          if (!(array && array.length)) {
            return result2;
          }
          var index2 = -1, indexes = [], length = array.length;
          predicate = getIteratee(predicate, 3);
          while (++index2 < length) {
            var value = array[index2];
            if (predicate(value, index2, array)) {
              result2.push(value);
              indexes.push(index2);
            }
          }
          basePullAt(array, indexes);
          return result2;
        }
        function reverse(array) {
          return array == null ? array : nativeReverse.call(array);
        }
        function slice(array, start, end) {
          var length = array == null ? 0 : array.length;
          if (!length) {
            return [];
          }
          if (end && typeof end != "number" && isIterateeCall(array, start, end)) {
            start = 0;
            end = length;
          } else {
            start = start == null ? 0 : toInteger(start);
            end = end === undefined$1 ? length : toInteger(end);
          }
          return baseSlice(array, start, end);
        }
        function sortedIndex(array, value) {
          return baseSortedIndex(array, value);
        }
        function sortedIndexBy(array, value, iteratee2) {
          return baseSortedIndexBy(array, value, getIteratee(iteratee2, 2));
        }
        function sortedIndexOf(array, value) {
          var length = array == null ? 0 : array.length;
          if (length) {
            var index2 = baseSortedIndex(array, value);
            if (index2 < length && eq(array[index2], value)) {
              return index2;
            }
          }
          return -1;
        }
        function sortedLastIndex(array, value) {
          return baseSortedIndex(array, value, true);
        }
        function sortedLastIndexBy(array, value, iteratee2) {
          return baseSortedIndexBy(array, value, getIteratee(iteratee2, 2), true);
        }
        function sortedLastIndexOf(array, value) {
          var length = array == null ? 0 : array.length;
          if (length) {
            var index2 = baseSortedIndex(array, value, true) - 1;
            if (eq(array[index2], value)) {
              return index2;
            }
          }
          return -1;
        }
        function sortedUniq(array) {
          return array && array.length ? baseSortedUniq(array) : [];
        }
        function sortedUniqBy(array, iteratee2) {
          return array && array.length ? baseSortedUniq(array, getIteratee(iteratee2, 2)) : [];
        }
        function tail(array) {
          var length = array == null ? 0 : array.length;
          return length ? baseSlice(array, 1, length) : [];
        }
        function take(array, n2, guard) {
          if (!(array && array.length)) {
            return [];
          }
          n2 = guard || n2 === undefined$1 ? 1 : toInteger(n2);
          return baseSlice(array, 0, n2 < 0 ? 0 : n2);
        }
        function takeRight(array, n2, guard) {
          var length = array == null ? 0 : array.length;
          if (!length) {
            return [];
          }
          n2 = guard || n2 === undefined$1 ? 1 : toInteger(n2);
          n2 = length - n2;
          return baseSlice(array, n2 < 0 ? 0 : n2, length);
        }
        function takeRightWhile(array, predicate) {
          return array && array.length ? baseWhile(array, getIteratee(predicate, 3), false, true) : [];
        }
        function takeWhile(array, predicate) {
          return array && array.length ? baseWhile(array, getIteratee(predicate, 3)) : [];
        }
        var union = baseRest(function(arrays) {
          return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
        });
        var unionBy = baseRest(function(arrays) {
          var iteratee2 = last(arrays);
          if (isArrayLikeObject(iteratee2)) {
            iteratee2 = undefined$1;
          }
          return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee2, 2));
        });
        var unionWith = baseRest(function(arrays) {
          var comparator = last(arrays);
          comparator = typeof comparator == "function" ? comparator : undefined$1;
          return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined$1, comparator);
        });
        function uniq(array) {
          return array && array.length ? baseUniq(array) : [];
        }
        function uniqBy(array, iteratee2) {
          return array && array.length ? baseUniq(array, getIteratee(iteratee2, 2)) : [];
        }
        function uniqWith(array, comparator) {
          comparator = typeof comparator == "function" ? comparator : undefined$1;
          return array && array.length ? baseUniq(array, undefined$1, comparator) : [];
        }
        function unzip(array) {
          if (!(array && array.length)) {
            return [];
          }
          var length = 0;
          array = arrayFilter(array, function(group) {
            if (isArrayLikeObject(group)) {
              length = nativeMax(group.length, length);
              return true;
            }
          });
          return baseTimes(length, function(index2) {
            return arrayMap(array, baseProperty(index2));
          });
        }
        function unzipWith(array, iteratee2) {
          if (!(array && array.length)) {
            return [];
          }
          var result2 = unzip(array);
          if (iteratee2 == null) {
            return result2;
          }
          return arrayMap(result2, function(group) {
            return apply(iteratee2, undefined$1, group);
          });
        }
        var without = baseRest(function(array, values2) {
          return isArrayLikeObject(array) ? baseDifference(array, values2) : [];
        });
        var xor = baseRest(function(arrays) {
          return baseXor(arrayFilter(arrays, isArrayLikeObject));
        });
        var xorBy = baseRest(function(arrays) {
          var iteratee2 = last(arrays);
          if (isArrayLikeObject(iteratee2)) {
            iteratee2 = undefined$1;
          }
          return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee2, 2));
        });
        var xorWith = baseRest(function(arrays) {
          var comparator = last(arrays);
          comparator = typeof comparator == "function" ? comparator : undefined$1;
          return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined$1, comparator);
        });
        var zip = baseRest(unzip);
        function zipObject(props, values2) {
          return baseZipObject(props || [], values2 || [], assignValue);
        }
        function zipObjectDeep(props, values2) {
          return baseZipObject(props || [], values2 || [], baseSet);
        }
        var zipWith = baseRest(function(arrays) {
          var length = arrays.length, iteratee2 = length > 1 ? arrays[length - 1] : undefined$1;
          iteratee2 = typeof iteratee2 == "function" ? (arrays.pop(), iteratee2) : undefined$1;
          return unzipWith(arrays, iteratee2);
        });
        function chain(value) {
          var result2 = lodash2(value);
          result2.__chain__ = true;
          return result2;
        }
        function tap(value, interceptor) {
          interceptor(value);
          return value;
        }
        function thru(value, interceptor) {
          return interceptor(value);
        }
        var wrapperAt = flatRest(function(paths) {
          var length = paths.length, start = length ? paths[0] : 0, value = this.__wrapped__, interceptor = function(object) {
            return baseAt(object, paths);
          };
          if (length > 1 || this.__actions__.length || !(value instanceof LazyWrapper) || !isIndex(start)) {
            return this.thru(interceptor);
          }
          value = value.slice(start, +start + (length ? 1 : 0));
          value.__actions__.push({
            "func": thru,
            "args": [interceptor],
            "thisArg": undefined$1
          });
          return new LodashWrapper(value, this.__chain__).thru(function(array) {
            if (length && !array.length) {
              array.push(undefined$1);
            }
            return array;
          });
        });
        function wrapperChain() {
          return chain(this);
        }
        function wrapperCommit() {
          return new LodashWrapper(this.value(), this.__chain__);
        }
        function wrapperNext() {
          if (this.__values__ === undefined$1) {
            this.__values__ = toArray(this.value());
          }
          var done = this.__index__ >= this.__values__.length, value = done ? undefined$1 : this.__values__[this.__index__++];
          return { "done": done, "value": value };
        }
        function wrapperToIterator() {
          return this;
        }
        function wrapperPlant(value) {
          var result2, parent2 = this;
          while (parent2 instanceof baseLodash) {
            var clone2 = wrapperClone(parent2);
            clone2.__index__ = 0;
            clone2.__values__ = undefined$1;
            if (result2) {
              previous.__wrapped__ = clone2;
            } else {
              result2 = clone2;
            }
            var previous = clone2;
            parent2 = parent2.__wrapped__;
          }
          previous.__wrapped__ = value;
          return result2;
        }
        function wrapperReverse() {
          var value = this.__wrapped__;
          if (value instanceof LazyWrapper) {
            var wrapped = value;
            if (this.__actions__.length) {
              wrapped = new LazyWrapper(this);
            }
            wrapped = wrapped.reverse();
            wrapped.__actions__.push({
              "func": thru,
              "args": [reverse],
              "thisArg": undefined$1
            });
            return new LodashWrapper(wrapped, this.__chain__);
          }
          return this.thru(reverse);
        }
        function wrapperValue() {
          return baseWrapperValue(this.__wrapped__, this.__actions__);
        }
        var countBy = createAggregator(function(result2, value, key) {
          if (hasOwnProperty.call(result2, key)) {
            ++result2[key];
          } else {
            baseAssignValue(result2, key, 1);
          }
        });
        function every(collection, predicate, guard) {
          var func = isArray(collection) ? arrayEvery : baseEvery;
          if (guard && isIterateeCall(collection, predicate, guard)) {
            predicate = undefined$1;
          }
          return func(collection, getIteratee(predicate, 3));
        }
        function filter(collection, predicate) {
          var func = isArray(collection) ? arrayFilter : baseFilter;
          return func(collection, getIteratee(predicate, 3));
        }
        var find = createFind(findIndex);
        var findLast = createFind(findLastIndex);
        function flatMap(collection, iteratee2) {
          return baseFlatten(map2(collection, iteratee2), 1);
        }
        function flatMapDeep(collection, iteratee2) {
          return baseFlatten(map2(collection, iteratee2), INFINITY);
        }
        function flatMapDepth(collection, iteratee2, depth) {
          depth = depth === undefined$1 ? 1 : toInteger(depth);
          return baseFlatten(map2(collection, iteratee2), depth);
        }
        function forEach(collection, iteratee2) {
          var func = isArray(collection) ? arrayEach : baseEach;
          return func(collection, getIteratee(iteratee2, 3));
        }
        function forEachRight(collection, iteratee2) {
          var func = isArray(collection) ? arrayEachRight : baseEachRight;
          return func(collection, getIteratee(iteratee2, 3));
        }
        var groupBy = createAggregator(function(result2, value, key) {
          if (hasOwnProperty.call(result2, key)) {
            result2[key].push(value);
          } else {
            baseAssignValue(result2, key, [value]);
          }
        });
        function includes(collection, value, fromIndex, guard) {
          collection = isArrayLike(collection) ? collection : values(collection);
          fromIndex = fromIndex && !guard ? toInteger(fromIndex) : 0;
          var length = collection.length;
          if (fromIndex < 0) {
            fromIndex = nativeMax(length + fromIndex, 0);
          }
          return isString(collection) ? fromIndex <= length && collection.indexOf(value, fromIndex) > -1 : !!length && baseIndexOf(collection, value, fromIndex) > -1;
        }
        var invokeMap = baseRest(function(collection, path, args) {
          var index2 = -1, isFunc = typeof path == "function", result2 = isArrayLike(collection) ? Array2(collection.length) : [];
          baseEach(collection, function(value) {
            result2[++index2] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);
          });
          return result2;
        });
        var keyBy = createAggregator(function(result2, value, key) {
          baseAssignValue(result2, key, value);
        });
        function map2(collection, iteratee2) {
          var func = isArray(collection) ? arrayMap : baseMap;
          return func(collection, getIteratee(iteratee2, 3));
        }
        function orderBy(collection, iteratees, orders, guard) {
          if (collection == null) {
            return [];
          }
          if (!isArray(iteratees)) {
            iteratees = iteratees == null ? [] : [iteratees];
          }
          orders = guard ? undefined$1 : orders;
          if (!isArray(orders)) {
            orders = orders == null ? [] : [orders];
          }
          return baseOrderBy(collection, iteratees, orders);
        }
        var partition = createAggregator(function(result2, value, key) {
          result2[key ? 0 : 1].push(value);
        }, function() {
          return [[], []];
        });
        function reduce(collection, iteratee2, accumulator) {
          var func = isArray(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3;
          return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEach);
        }
        function reduceRight(collection, iteratee2, accumulator) {
          var func = isArray(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3;
          return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEachRight);
        }
        function reject(collection, predicate) {
          var func = isArray(collection) ? arrayFilter : baseFilter;
          return func(collection, negate(getIteratee(predicate, 3)));
        }
        function sample(collection) {
          var func = isArray(collection) ? arraySample : baseSample;
          return func(collection);
        }
        function sampleSize(collection, n2, guard) {
          if (guard ? isIterateeCall(collection, n2, guard) : n2 === undefined$1) {
            n2 = 1;
          } else {
            n2 = toInteger(n2);
          }
          var func = isArray(collection) ? arraySampleSize : baseSampleSize;
          return func(collection, n2);
        }
        function shuffle(collection) {
          var func = isArray(collection) ? arrayShuffle : baseShuffle;
          return func(collection);
        }
        function size(collection) {
          if (collection == null) {
            return 0;
          }
          if (isArrayLike(collection)) {
            return isString(collection) ? stringSize(collection) : collection.length;
          }
          var tag = getTag(collection);
          if (tag == mapTag || tag == setTag) {
            return collection.size;
          }
          return baseKeys(collection).length;
        }
        function some(collection, predicate, guard) {
          var func = isArray(collection) ? arraySome : baseSome;
          if (guard && isIterateeCall(collection, predicate, guard)) {
            predicate = undefined$1;
          }
          return func(collection, getIteratee(predicate, 3));
        }
        var sortBy = baseRest(function(collection, iteratees) {
          if (collection == null) {
            return [];
          }
          var length = iteratees.length;
          if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
            iteratees = [];
          } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
            iteratees = [iteratees[0]];
          }
          return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
        });
        var now = ctxNow || function() {
          return root.Date.now();
        };
        function after(n2, func) {
          if (typeof func != "function") {
            throw new TypeError2(FUNC_ERROR_TEXT);
          }
          n2 = toInteger(n2);
          return function() {
            if (--n2 < 1) {
              return func.apply(this, arguments);
            }
          };
        }
        function ary(func, n2, guard) {
          n2 = guard ? undefined$1 : n2;
          n2 = func && n2 == null ? func.length : n2;
          return createWrap(func, WRAP_ARY_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, n2);
        }
        function before(n2, func) {
          var result2;
          if (typeof func != "function") {
            throw new TypeError2(FUNC_ERROR_TEXT);
          }
          n2 = toInteger(n2);
          return function() {
            if (--n2 > 0) {
              result2 = func.apply(this, arguments);
            }
            if (n2 <= 1) {
              func = undefined$1;
            }
            return result2;
          };
        }
        var bind = baseRest(function(func, thisArg, partials) {
          var bitmask = WRAP_BIND_FLAG;
          if (partials.length) {
            var holders = replaceHolders(partials, getHolder(bind));
            bitmask |= WRAP_PARTIAL_FLAG;
          }
          return createWrap(func, bitmask, thisArg, partials, holders);
        });
        var bindKey = baseRest(function(object, key, partials) {
          var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
          if (partials.length) {
            var holders = replaceHolders(partials, getHolder(bindKey));
            bitmask |= WRAP_PARTIAL_FLAG;
          }
          return createWrap(key, bitmask, object, partials, holders);
        });
        function curry(func, arity, guard) {
          arity = guard ? undefined$1 : arity;
          var result2 = createWrap(func, WRAP_CURRY_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, undefined$1, arity);
          result2.placeholder = curry.placeholder;
          return result2;
        }
        function curryRight(func, arity, guard) {
          arity = guard ? undefined$1 : arity;
          var result2 = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, undefined$1, arity);
          result2.placeholder = curryRight.placeholder;
          return result2;
        }
        function debounce(func, wait, options) {
          var lastArgs, lastThis, maxWait, result2, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true;
          if (typeof func != "function") {
            throw new TypeError2(FUNC_ERROR_TEXT);
          }
          wait = toNumber(wait) || 0;
          if (isObject2(options)) {
            leading = !!options.leading;
            maxing = "maxWait" in options;
            maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
            trailing = "trailing" in options ? !!options.trailing : trailing;
          }
          function invokeFunc(time) {
            var args = lastArgs, thisArg = lastThis;
            lastArgs = lastThis = undefined$1;
            lastInvokeTime = time;
            result2 = func.apply(thisArg, args);
            return result2;
          }
          function leadingEdge(time) {
            lastInvokeTime = time;
            timerId = setTimeout2(timerExpired, wait);
            return leading ? invokeFunc(time) : result2;
          }
          function remainingWait(time) {
            var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall;
            return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting;
          }
          function shouldInvoke(time) {
            var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime;
            return lastCallTime === undefined$1 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait;
          }
          function timerExpired() {
            var time = now();
            if (shouldInvoke(time)) {
              return trailingEdge(time);
            }
            timerId = setTimeout2(timerExpired, remainingWait(time));
          }
          function trailingEdge(time) {
            timerId = undefined$1;
            if (trailing && lastArgs) {
              return invokeFunc(time);
            }
            lastArgs = lastThis = undefined$1;
            return result2;
          }
          function cancel() {
            if (timerId !== undefined$1) {
              clearTimeout2(timerId);
            }
            lastInvokeTime = 0;
            lastArgs = lastCallTime = lastThis = timerId = undefined$1;
          }
          function flush() {
            return timerId === undefined$1 ? result2 : trailingEdge(now());
          }
          function debounced() {
            var time = now(), isInvoking = shouldInvoke(time);
            lastArgs = arguments;
            lastThis = this;
            lastCallTime = time;
            if (isInvoking) {
              if (timerId === undefined$1) {
                return leadingEdge(lastCallTime);
              }
              if (maxing) {
                clearTimeout2(timerId);
                timerId = setTimeout2(timerExpired, wait);
                return invokeFunc(lastCallTime);
              }
            }
            if (timerId === undefined$1) {
              timerId = setTimeout2(timerExpired, wait);
            }
            return result2;
          }
          debounced.cancel = cancel;
          debounced.flush = flush;
          return debounced;
        }
        var defer2 = baseRest(function(func, args) {
          return baseDelay(func, 1, args);
        });
        var delay = baseRest(function(func, wait, args) {
          return baseDelay(func, toNumber(wait) || 0, args);
        });
        function flip(func) {
          return createWrap(func, WRAP_FLIP_FLAG);
        }
        function memoize(func, resolver) {
          if (typeof func != "function" || resolver != null && typeof resolver != "function") {
            throw new TypeError2(FUNC_ERROR_TEXT);
          }
          var memoized = function() {
            var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache;
            if (cache.has(key)) {
              return cache.get(key);
            }
            var result2 = func.apply(this, args);
            memoized.cache = cache.set(key, result2) || cache;
            return result2;
          };
          memoized.cache = new (memoize.Cache || MapCache)();
          return memoized;
        }
        memoize.Cache = MapCache;
        function negate(predicate) {
          if (typeof predicate != "function") {
            throw new TypeError2(FUNC_ERROR_TEXT);
          }
          return function() {
            var args = arguments;
            switch (args.length) {
              case 0:
                return !predicate.call(this);
              case 1:
                return !predicate.call(this, args[0]);
              case 2:
                return !predicate.call(this, args[0], args[1]);
              case 3:
                return !predicate.call(this, args[0], args[1], args[2]);
            }
            return !predicate.apply(this, args);
          };
        }
        function once(func) {
          return before(2, func);
        }
        var overArgs = castRest(function(func, transforms) {
          transforms = transforms.length == 1 && isArray(transforms[0]) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));
          var funcsLength = transforms.length;
          return baseRest(function(args) {
            var index2 = -1, length = nativeMin(args.length, funcsLength);
            while (++index2 < length) {
              args[index2] = transforms[index2].call(this, args[index2]);
            }
            return apply(func, this, args);
          });
        });
        var partial = baseRest(function(func, partials) {
          var holders = replaceHolders(partials, getHolder(partial));
          return createWrap(func, WRAP_PARTIAL_FLAG, undefined$1, partials, holders);
        });
        var partialRight = baseRest(function(func, partials) {
          var holders = replaceHolders(partials, getHolder(partialRight));
          return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined$1, partials, holders);
        });
        var rearg = flatRest(function(func, indexes) {
          return createWrap(func, WRAP_REARG_FLAG, undefined$1, undefined$1, undefined$1, indexes);
        });
        function rest(func, start) {
          if (typeof func != "function") {
            throw new TypeError2(FUNC_ERROR_TEXT);
          }
          start = start === undefined$1 ? start : toInteger(start);
          return baseRest(func, start);
        }
        function spread(func, start) {
          if (typeof func != "function") {
            throw new TypeError2(FUNC_ERROR_TEXT);
          }
          start = start == null ? 0 : nativeMax(toInteger(start), 0);
          return baseRest(function(args) {
            var array = args[start], otherArgs = castSlice(args, 0, start);
            if (array) {
              arrayPush(otherArgs, array);
            }
            return apply(func, this, otherArgs);
          });
        }
        function throttle(func, wait, options) {
          var leading = true, trailing = true;
          if (typeof func != "function") {
            throw new TypeError2(FUNC_ERROR_TEXT);
          }
          if (isObject2(options)) {
            leading = "leading" in options ? !!options.leading : leading;
            trailing = "trailing" in options ? !!options.trailing : trailing;
          }
          return debounce(func, wait, {
            "leading": leading,
            "maxWait": wait,
            "trailing": trailing
          });
        }
        function unary(func) {
          return ary(func, 1);
        }
        function wrap2(value, wrapper) {
          return partial(castFunction(wrapper), value);
        }
        function castArray() {
          if (!arguments.length) {
            return [];
          }
          var value = arguments[0];
          return isArray(value) ? value : [value];
        }
        function clone(value) {
          return baseClone(value, CLONE_SYMBOLS_FLAG);
        }
        function cloneWith(value, customizer) {
          customizer = typeof customizer == "function" ? customizer : undefined$1;
          return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);
        }
        function cloneDeep(value) {
          return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
        }
        function cloneDeepWith(value, customizer) {
          customizer = typeof customizer == "function" ? customizer : undefined$1;
          return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);
        }
        function conformsTo(object, source) {
          return source == null || baseConformsTo(object, source, keys(source));
        }
        function eq(value, other) {
          return value === other || value !== value && other !== other;
        }
        var gt = createRelationalOperation(baseGt);
        var gte = createRelationalOperation(function(value, other) {
          return value >= other;
        });
        var isArguments = baseIsArguments(function() {
          return arguments;
        }()) ? baseIsArguments : function(value) {
          return isObjectLike(value) && hasOwnProperty.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
        };
        var isArray = Array2.isArray;
        var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;
        function isArrayLike(value) {
          return value != null && isLength(value.length) && !isFunction(value);
        }
        function isArrayLikeObject(value) {
          return isObjectLike(value) && isArrayLike(value);
        }
        function isBoolean(value) {
          return value === true || value === false || isObjectLike(value) && baseGetTag(value) == boolTag;
        }
        var isBuffer = nativeIsBuffer || stubFalse;
        var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;
        function isElement(value) {
          return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);
        }
        function isEmpty2(value) {
          if (value == null) {
            return true;
          }
          if (isArrayLike(value) && (isArray(value) || typeof value == "string" || typeof value.splice == "function" || isBuffer(value) || isTypedArray(value) || isArguments(value))) {
            return !value.length;
          }
          var tag = getTag(value);
          if (tag == mapTag || tag == setTag) {
            return !value.size;
          }
          if (isPrototype(value)) {
            return !baseKeys(value).length;
          }
          for (var key in value) {
            if (hasOwnProperty.call(value, key)) {
              return false;
            }
          }
          return true;
        }
        function isEqual(value, other) {
          return baseIsEqual(value, other);
        }
        function isEqualWith(value, other, customizer) {
          customizer = typeof customizer == "function" ? customizer : undefined$1;
          var result2 = customizer ? customizer(value, other) : undefined$1;
          return result2 === undefined$1 ? baseIsEqual(value, other, undefined$1, customizer) : !!result2;
        }
        function isError(value) {
          if (!isObjectLike(value)) {
            return false;
          }
          var tag = baseGetTag(value);
          return tag == errorTag || tag == domExcTag || typeof value.message == "string" && typeof value.name == "string" && !isPlainObject(value);
        }
        function isFinite(value) {
          return typeof value == "number" && nativeIsFinite(value);
        }
        function isFunction(value) {
          if (!isObject2(value)) {
            return false;
          }
          var tag = baseGetTag(value);
          return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
        }
        function isInteger(value) {
          return typeof value == "number" && value == toInteger(value);
        }
        function isLength(value) {
          return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
        }
        function isObject2(value) {
          var type = typeof value;
          return value != null && (type == "object" || type == "function");
        }
        function isObjectLike(value) {
          return value != null && typeof value == "object";
        }
        var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
        function isMatch(object, source) {
          return object === source || baseIsMatch(object, source, getMatchData(source));
        }
        function isMatchWith(object, source, customizer) {
          customizer = typeof customizer == "function" ? customizer : undefined$1;
          return baseIsMatch(object, source, getMatchData(source), customizer);
        }
        function isNaN2(value) {
          return isNumber(value) && value != +value;
        }
        function isNative(value) {
          if (isMaskable(value)) {
            throw new Error2(CORE_ERROR_TEXT);
          }
          return baseIsNative(value);
        }
        function isNull(value) {
          return value === null;
        }
        function isNil(value) {
          return value == null;
        }
        function isNumber(value) {
          return typeof value == "number" || isObjectLike(value) && baseGetTag(value) == numberTag;
        }
        function isPlainObject(value) {
          if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
            return false;
          }
          var proto = getPrototype(value);
          if (proto === null) {
            return true;
          }
          var Ctor = hasOwnProperty.call(proto, "constructor") && proto.constructor;
          return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString;
        }
        var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;
        function isSafeInteger(value) {
          return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
        }
        var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
        function isString(value) {
          return typeof value == "string" || !isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag;
        }
        function isSymbol(value) {
          return typeof value == "symbol" || isObjectLike(value) && baseGetTag(value) == symbolTag;
        }
        var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
        function isUndefined(value) {
          return value === undefined$1;
        }
        function isWeakMap(value) {
          return isObjectLike(value) && getTag(value) == weakMapTag;
        }
        function isWeakSet(value) {
          return isObjectLike(value) && baseGetTag(value) == weakSetTag;
        }
        var lt = createRelationalOperation(baseLt);
        var lte = createRelationalOperation(function(value, other) {
          return value <= other;
        });
        function toArray(value) {
          if (!value) {
            return [];
          }
          if (isArrayLike(value)) {
            return isString(value) ? stringToArray(value) : copyArray(value);
          }
          if (symIterator && value[symIterator]) {
            return iteratorToArray(value[symIterator]());
          }
          var tag = getTag(value), func = tag == mapTag ? mapToArray : tag == setTag ? setToArray : values;
          return func(value);
        }
        function toFinite(value) {
          if (!value) {
            return value === 0 ? value : 0;
          }
          value = toNumber(value);
          if (value === INFINITY || value === -INFINITY) {
            var sign = value < 0 ? -1 : 1;
            return sign * MAX_INTEGER;
          }
          return value === value ? value : 0;
        }
        function toInteger(value) {
          var result2 = toFinite(value), remainder = result2 % 1;
          return result2 === result2 ? remainder ? result2 - remainder : result2 : 0;
        }
        function toLength(value) {
          return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
        }
        function toNumber(value) {
          if (typeof value == "number") {
            return value;
          }
          if (isSymbol(value)) {
            return NAN;
          }
          if (isObject2(value)) {
            var other = typeof value.valueOf == "function" ? value.valueOf() : value;
            value = isObject2(other) ? other + "" : other;
          }
          if (typeof value != "string") {
            return value === 0 ? value : +value;
          }
          value = baseTrim(value);
          var isBinary = reIsBinary.test(value);
          return isBinary || reIsOctal.test(value) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value) ? NAN : +value;
        }
        function toPlainObject(value) {
          return copyObject(value, keysIn(value));
        }
        function toSafeInteger(value) {
          return value ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) : value === 0 ? value : 0;
        }
        function toString(value) {
          return value == null ? "" : baseToString(value);
        }
        var assign = createAssigner(function(object, source) {
          if (isPrototype(source) || isArrayLike(source)) {
            copyObject(source, keys(source), object);
            return;
          }
          for (var key in source) {
            if (hasOwnProperty.call(source, key)) {
              assignValue(object, key, source[key]);
            }
          }
        });
        var assignIn = createAssigner(function(object, source) {
          copyObject(source, keysIn(source), object);
        });
        var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
          copyObject(source, keysIn(source), object, customizer);
        });
        var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
          copyObject(source, keys(source), object, customizer);
        });
        var at = flatRest(baseAt);
        function create(prototype, properties2) {
          var result2 = baseCreate(prototype);
          return properties2 == null ? result2 : baseAssign(result2, properties2);
        }
        var defaults = baseRest(function(object, sources) {
          object = Object2(object);
          var index2 = -1;
          var length = sources.length;
          var guard = length > 2 ? sources[2] : undefined$1;
          if (guard && isIterateeCall(sources[0], sources[1], guard)) {
            length = 1;
          }
          while (++index2 < length) {
            var source = sources[index2];
            var props = keysIn(source);
            var propsIndex = -1;
            var propsLength = props.length;
            while (++propsIndex < propsLength) {
              var key = props[propsIndex];
              var value = object[key];
              if (value === undefined$1 || eq(value, objectProto[key]) && !hasOwnProperty.call(object, key)) {
                object[key] = source[key];
              }
            }
          }
          return object;
        });
        var defaultsDeep = baseRest(function(args) {
          args.push(undefined$1, customDefaultsMerge);
          return apply(mergeWith, undefined$1, args);
        });
        function findKey(object, predicate) {
          return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);
        }
        function findLastKey(object, predicate) {
          return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
        }
        function forIn(object, iteratee2) {
          return object == null ? object : baseFor(object, getIteratee(iteratee2, 3), keysIn);
        }
        function forInRight(object, iteratee2) {
          return object == null ? object : baseForRight(object, getIteratee(iteratee2, 3), keysIn);
        }
        function forOwn(object, iteratee2) {
          return object && baseForOwn(object, getIteratee(iteratee2, 3));
        }
        function forOwnRight(object, iteratee2) {
          return object && baseForOwnRight(object, getIteratee(iteratee2, 3));
        }
        function functions(object) {
          return object == null ? [] : baseFunctions(object, keys(object));
        }
        function functionsIn(object) {
          return object == null ? [] : baseFunctions(object, keysIn(object));
        }
        function get2(object, path, defaultValue2) {
          var result2 = object == null ? undefined$1 : baseGet(object, path);
          return result2 === undefined$1 ? defaultValue2 : result2;
        }
        function has(object, path) {
          return object != null && hasPath(object, path, baseHas);
        }
        function hasIn(object, path) {
          return object != null && hasPath(object, path, baseHasIn);
        }
        var invert = createInverter(function(result2, value, key) {
          if (value != null && typeof value.toString != "function") {
            value = nativeObjectToString.call(value);
          }
          result2[value] = key;
        }, constant(identity));
        var invertBy = createInverter(function(result2, value, key) {
          if (value != null && typeof value.toString != "function") {
            value = nativeObjectToString.call(value);
          }
          if (hasOwnProperty.call(result2, value)) {
            result2[value].push(key);
          } else {
            result2[value] = [key];
          }
        }, getIteratee);
        var invoke = baseRest(baseInvoke);
        function keys(object) {
          return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
        }
        function keysIn(object) {
          return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
        }
        function mapKeys(object, iteratee2) {
          var result2 = {};
          iteratee2 = getIteratee(iteratee2, 3);
          baseForOwn(object, function(value, key, object2) {
            baseAssignValue(result2, iteratee2(value, key, object2), value);
          });
          return result2;
        }
        function mapValues(object, iteratee2) {
          var result2 = {};
          iteratee2 = getIteratee(iteratee2, 3);
          baseForOwn(object, function(value, key, object2) {
            baseAssignValue(result2, key, iteratee2(value, key, object2));
          });
          return result2;
        }
        var merge = createAssigner(function(object, source, srcIndex) {
          baseMerge(object, source, srcIndex);
        });
        var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
          baseMerge(object, source, srcIndex, customizer);
        });
        var omit = flatRest(function(object, paths) {
          var result2 = {};
          if (object == null) {
            return result2;
          }
          var isDeep = false;
          paths = arrayMap(paths, function(path) {
            path = castPath(path, object);
            isDeep || (isDeep = path.length > 1);
            return path;
          });
          copyObject(object, getAllKeysIn(object), result2);
          if (isDeep) {
            result2 = baseClone(result2, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
          }
          var length = paths.length;
          while (length--) {
            baseUnset(result2, paths[length]);
          }
          return result2;
        });
        function omitBy(object, predicate) {
          return pickBy(object, negate(getIteratee(predicate)));
        }
        var pick = flatRest(function(object, paths) {
          return object == null ? {} : basePick(object, paths);
        });
        function pickBy(object, predicate) {
          if (object == null) {
            return {};
          }
          var props = arrayMap(getAllKeysIn(object), function(prop) {
            return [prop];
          });
          predicate = getIteratee(predicate);
          return basePickBy(object, props, function(value, path) {
            return predicate(value, path[0]);
          });
        }
        function result(object, path, defaultValue2) {
          path = castPath(path, object);
          var index2 = -1, length = path.length;
          if (!length) {
            length = 1;
            object = undefined$1;
          }
          while (++index2 < length) {
            var value = object == null ? undefined$1 : object[toKey(path[index2])];
            if (value === undefined$1) {
              index2 = length;
              value = defaultValue2;
            }
            object = isFunction(value) ? value.call(object) : value;
          }
          return object;
        }
        function set2(object, path, value) {
          return object == null ? object : baseSet(object, path, value);
        }
        function setWith(object, path, value, customizer) {
          customizer = typeof customizer == "function" ? customizer : undefined$1;
          return object == null ? object : baseSet(object, path, value, customizer);
        }
        var toPairs = createToPairs(keys);
        var toPairsIn = createToPairs(keysIn);
        function transform(object, iteratee2, accumulator) {
          var isArr = isArray(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object);
          iteratee2 = getIteratee(iteratee2, 4);
          if (accumulator == null) {
            var Ctor = object && object.constructor;
            if (isArrLike) {
              accumulator = isArr ? new Ctor() : [];
            } else if (isObject2(object)) {
              accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
            } else {
              accumulator = {};
            }
          }
          (isArrLike ? arrayEach : baseForOwn)(object, function(value, index2, object2) {
            return iteratee2(accumulator, value, index2, object2);
          });
          return accumulator;
        }
        function unset(object, path) {
          return object == null ? true : baseUnset(object, path);
        }
        function update(object, path, updater) {
          return object == null ? object : baseUpdate(object, path, castFunction(updater));
        }
        function updateWith(object, path, updater, customizer) {
          customizer = typeof customizer == "function" ? customizer : undefined$1;
          return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
        }
        function values(object) {
          return object == null ? [] : baseValues(object, keys(object));
        }
        function valuesIn(object) {
          return object == null ? [] : baseValues(object, keysIn(object));
        }
        function clamp(number, lower, upper) {
          if (upper === undefined$1) {
            upper = lower;
            lower = undefined$1;
          }
          if (upper !== undefined$1) {
            upper = toNumber(upper);
            upper = upper === upper ? upper : 0;
          }
          if (lower !== undefined$1) {
            lower = toNumber(lower);
            lower = lower === lower ? lower : 0;
          }
          return baseClamp(toNumber(number), lower, upper);
        }
        function inRange(number, start, end) {
          start = toFinite(start);
          if (end === undefined$1) {
            end = start;
            start = 0;
          } else {
            end = toFinite(end);
          }
          number = toNumber(number);
          return baseInRange(number, start, end);
        }
        function random(lower, upper, floating) {
          if (floating && typeof floating != "boolean" && isIterateeCall(lower, upper, floating)) {
            upper = floating = undefined$1;
          }
          if (floating === undefined$1) {
            if (typeof upper == "boolean") {
              floating = upper;
              upper = undefined$1;
            } else if (typeof lower == "boolean") {
              floating = lower;
              lower = undefined$1;
            }
          }
          if (lower === undefined$1 && upper === undefined$1) {
            lower = 0;
            upper = 1;
          } else {
            lower = toFinite(lower);
            if (upper === undefined$1) {
              upper = lower;
              lower = 0;
            } else {
              upper = toFinite(upper);
            }
          }
          if (lower > upper) {
            var temp = lower;
            lower = upper;
            upper = temp;
          }
          if (floating || lower % 1 || upper % 1) {
            var rand = nativeRandom();
            return nativeMin(lower + rand * (upper - lower + freeParseFloat("1e-" + ((rand + "").length - 1))), upper);
          }
          return baseRandom(lower, upper);
        }
        var camelCase = createCompounder(function(result2, word, index2) {
          word = word.toLowerCase();
          return result2 + (index2 ? capitalize2(word) : word);
        });
        function capitalize2(string) {
          return upperFirst(toString(string).toLowerCase());
        }
        function deburr(string) {
          string = toString(string);
          return string && string.replace(reLatin, deburrLetter).replace(reComboMark, "");
        }
        function endsWith(string, target, position) {
          string = toString(string);
          target = baseToString(target);
          var length = string.length;
          position = position === undefined$1 ? length : baseClamp(toInteger(position), 0, length);
          var end = position;
          position -= target.length;
          return position >= 0 && string.slice(position, end) == target;
        }
        function escape2(string) {
          string = toString(string);
          return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string;
        }
        function escapeRegExp(string) {
          string = toString(string);
          return string && reHasRegExpChar.test(string) ? string.replace(reRegExpChar, "\\$&") : string;
        }
        var kebabCase = createCompounder(function(result2, word, index2) {
          return result2 + (index2 ? "-" : "") + word.toLowerCase();
        });
        var lowerCase = createCompounder(function(result2, word, index2) {
          return result2 + (index2 ? " " : "") + word.toLowerCase();
        });
        var lowerFirst = createCaseFirst("toLowerCase");
        function pad(string, length, chars2) {
          string = toString(string);
          length = toInteger(length);
          var strLength = length ? stringSize(string) : 0;
          if (!length || strLength >= length) {
            return string;
          }
          var mid = (length - strLength) / 2;
          return createPadding(nativeFloor(mid), chars2) + string + createPadding(nativeCeil(mid), chars2);
        }
        function padEnd(string, length, chars2) {
          string = toString(string);
          length = toInteger(length);
          var strLength = length ? stringSize(string) : 0;
          return length && strLength < length ? string + createPadding(length - strLength, chars2) : string;
        }
        function padStart(string, length, chars2) {
          string = toString(string);
          length = toInteger(length);
          var strLength = length ? stringSize(string) : 0;
          return length && strLength < length ? createPadding(length - strLength, chars2) + string : string;
        }
        function parseInt2(string, radix, guard) {
          if (guard || radix == null) {
            radix = 0;
          } else if (radix) {
            radix = +radix;
          }
          return nativeParseInt(toString(string).replace(reTrimStart, ""), radix || 0);
        }
        function repeat(string, n2, guard) {
          if (guard ? isIterateeCall(string, n2, guard) : n2 === undefined$1) {
            n2 = 1;
          } else {
            n2 = toInteger(n2);
          }
          return baseRepeat(toString(string), n2);
        }
        function replace() {
          var args = arguments, string = toString(args[0]);
          return args.length < 3 ? string : string.replace(args[1], args[2]);
        }
        var snakeCase = createCompounder(function(result2, word, index2) {
          return result2 + (index2 ? "_" : "") + word.toLowerCase();
        });
        function split(string, separator, limit) {
          if (limit && typeof limit != "number" && isIterateeCall(string, separator, limit)) {
            separator = limit = undefined$1;
          }
          limit = limit === undefined$1 ? MAX_ARRAY_LENGTH : limit >>> 0;
          if (!limit) {
            return [];
          }
          string = toString(string);
          if (string && (typeof separator == "string" || separator != null && !isRegExp(separator))) {
            separator = baseToString(separator);
            if (!separator && hasUnicode(string)) {
              return castSlice(stringToArray(string), 0, limit);
            }
          }
          return string.split(separator, limit);
        }
        var startCase = createCompounder(function(result2, word, index2) {
          return result2 + (index2 ? " " : "") + upperFirst(word);
        });
        function startsWith(string, target, position) {
          string = toString(string);
          position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length);
          target = baseToString(target);
          return string.slice(position, position + target.length) == target;
        }
        function template(string, options, guard) {
          var settings2 = lodash2.templateSettings;
          if (guard && isIterateeCall(string, options, guard)) {
            options = undefined$1;
          }
          string = toString(string);
          options = assignInWith({}, options, settings2, customDefaultsAssignIn);
          var imports = assignInWith({}, options.imports, settings2.imports, customDefaultsAssignIn), importsKeys = keys(imports), importsValues = baseValues(imports, importsKeys);
          var isEscaping, isEvaluating, index2 = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '";
          var reDelimiters = RegExp2(
            (options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$",
            "g"
          );
          var sourceURL = "//# sourceURL=" + (hasOwnProperty.call(options, "sourceURL") ? (options.sourceURL + "").replace(/\s/g, " ") : "lodash.templateSources[" + ++templateCounter + "]") + "\n";
          string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
            interpolateValue || (interpolateValue = esTemplateValue);
            source += string.slice(index2, offset).replace(reUnescapedString, escapeStringChar);
            if (escapeValue) {
              isEscaping = true;
              source += "' +\n__e(" + escapeValue + ") +\n'";
            }
            if (evaluateValue) {
              isEvaluating = true;
              source += "';\n" + evaluateValue + ";\n__p += '";
            }
            if (interpolateValue) {
              source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
            }
            index2 = offset + match.length;
            return match;
          });
          source += "';\n";
          var variable = hasOwnProperty.call(options, "variable") && options.variable;
          if (!variable) {
            source = "with (obj) {\n" + source + "\n}\n";
          } else if (reForbiddenIdentifierChars.test(variable)) {
            throw new Error2(INVALID_TEMPL_VAR_ERROR_TEXT);
          }
          source = (isEvaluating ? source.replace(reEmptyStringLeading, "") : source).replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;");
          source = "function(" + (variable || "obj") + ") {\n" + (variable ? "" : "obj || (obj = {});\n") + "var __t, __p = ''" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n" : ";\n") + source + "return __p\n}";
          var result2 = attempt(function() {
            return Function2(importsKeys, sourceURL + "return " + source).apply(undefined$1, importsValues);
          });
          result2.source = source;
          if (isError(result2)) {
            throw result2;
          }
          return result2;
        }
        function toLower(value) {
          return toString(value).toLowerCase();
        }
        function toUpper(value) {
          return toString(value).toUpperCase();
        }
        function trim(string, chars2, guard) {
          string = toString(string);
          if (string && (guard || chars2 === undefined$1)) {
            return baseTrim(string);
          }
          if (!string || !(chars2 = baseToString(chars2))) {
            return string;
          }
          var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars2), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1;
          return castSlice(strSymbols, start, end).join("");
        }
        function trimEnd(string, chars2, guard) {
          string = toString(string);
          if (string && (guard || chars2 === undefined$1)) {
            return string.slice(0, trimmedEndIndex(string) + 1);
          }
          if (!string || !(chars2 = baseToString(chars2))) {
            return string;
          }
          var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars2)) + 1;
          return castSlice(strSymbols, 0, end).join("");
        }
        function trimStart(string, chars2, guard) {
          string = toString(string);
          if (string && (guard || chars2 === undefined$1)) {
            return string.replace(reTrimStart, "");
          }
          if (!string || !(chars2 = baseToString(chars2))) {
            return string;
          }
          var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars2));
          return castSlice(strSymbols, start).join("");
        }
        function truncate(string, options) {
          var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION;
          if (isObject2(options)) {
            var separator = "separator" in options ? options.separator : separator;
            length = "length" in options ? toInteger(options.length) : length;
            omission = "omission" in options ? baseToString(options.omission) : omission;
          }
          string = toString(string);
          var strLength = string.length;
          if (hasUnicode(string)) {
            var strSymbols = stringToArray(string);
            strLength = strSymbols.length;
          }
          if (length >= strLength) {
            return string;
          }
          var end = length - stringSize(omission);
          if (end < 1) {
            return omission;
          }
          var result2 = strSymbols ? castSlice(strSymbols, 0, end).join("") : string.slice(0, end);
          if (separator === undefined$1) {
            return result2 + omission;
          }
          if (strSymbols) {
            end += result2.length - end;
          }
          if (isRegExp(separator)) {
            if (string.slice(end).search(separator)) {
              var match, substring = result2;
              if (!separator.global) {
                separator = RegExp2(separator.source, toString(reFlags.exec(separator)) + "g");
              }
              separator.lastIndex = 0;
              while (match = separator.exec(substring)) {
                var newEnd = match.index;
              }
              result2 = result2.slice(0, newEnd === undefined$1 ? end : newEnd);
            }
          } else if (string.indexOf(baseToString(separator), end) != end) {
            var index2 = result2.lastIndexOf(separator);
            if (index2 > -1) {
              result2 = result2.slice(0, index2);
            }
          }
          return result2 + omission;
        }
        function unescape2(string) {
          string = toString(string);
          return string && reHasEscapedHtml.test(string) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string;
        }
        var upperCase = createCompounder(function(result2, word, index2) {
          return result2 + (index2 ? " " : "") + word.toUpperCase();
        });
        var upperFirst = createCaseFirst("toUpperCase");
        function words(string, pattern, guard) {
          string = toString(string);
          pattern = guard ? undefined$1 : pattern;
          if (pattern === undefined$1) {
            return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
          }
          return string.match(pattern) || [];
        }
        var attempt = baseRest(function(func, args) {
          try {
            return apply(func, undefined$1, args);
          } catch (e2) {
            return isError(e2) ? e2 : new Error2(e2);
          }
        });
        var bindAll = flatRest(function(object, methodNames) {
          arrayEach(methodNames, function(key) {
            key = toKey(key);
            baseAssignValue(object, key, bind(object[key], object));
          });
          return object;
        });
        function cond(pairs) {
          var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee();
          pairs = !length ? [] : arrayMap(pairs, function(pair) {
            if (typeof pair[1] != "function") {
              throw new TypeError2(FUNC_ERROR_TEXT);
            }
            return [toIteratee(pair[0]), pair[1]];
          });
          return baseRest(function(args) {
            var index2 = -1;
            while (++index2 < length) {
              var pair = pairs[index2];
              if (apply(pair[0], this, args)) {
                return apply(pair[1], this, args);
              }
            }
          });
        }
        function conforms(source) {
          return baseConforms(baseClone(source, CLONE_DEEP_FLAG));
        }
        function constant(value) {
          return function() {
            return value;
          };
        }
        function defaultTo(value, defaultValue2) {
          return value == null || value !== value ? defaultValue2 : value;
        }
        var flow = createFlow();
        var flowRight = createFlow(true);
        function identity(value) {
          return value;
        }
        function iteratee(func) {
          return baseIteratee(typeof func == "function" ? func : baseClone(func, CLONE_DEEP_FLAG));
        }
        function matches(source) {
          return baseMatches(baseClone(source, CLONE_DEEP_FLAG));
        }
        function matchesProperty(path, srcValue) {
          return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG));
        }
        var method = baseRest(function(path, args) {
          return function(object) {
            return baseInvoke(object, path, args);
          };
        });
        var methodOf = baseRest(function(object, args) {
          return function(path) {
            return baseInvoke(object, path, args);
          };
        });
        function mixin(object, source, options) {
          var props = keys(source), methodNames = baseFunctions(source, props);
          if (options == null && !(isObject2(source) && (methodNames.length || !props.length))) {
            options = source;
            source = object;
            object = this;
            methodNames = baseFunctions(source, keys(source));
          }
          var chain2 = !(isObject2(options) && "chain" in options) || !!options.chain, isFunc = isFunction(object);
          arrayEach(methodNames, function(methodName) {
            var func = source[methodName];
            object[methodName] = func;
            if (isFunc) {
              object.prototype[methodName] = function() {
                var chainAll = this.__chain__;
                if (chain2 || chainAll) {
                  var result2 = object(this.__wrapped__), actions = result2.__actions__ = copyArray(this.__actions__);
                  actions.push({ "func": func, "args": arguments, "thisArg": object });
                  result2.__chain__ = chainAll;
                  return result2;
                }
                return func.apply(object, arrayPush([this.value()], arguments));
              };
            }
          });
          return object;
        }
        function noConflict() {
          if (root._ === this) {
            root._ = oldDash;
          }
          return this;
        }
        function noop2() {
        }
        function nthArg(n2) {
          n2 = toInteger(n2);
          return baseRest(function(args) {
            return baseNth(args, n2);
          });
        }
        var over = createOver(arrayMap);
        var overEvery = createOver(arrayEvery);
        var overSome = createOver(arraySome);
        function property(path) {
          return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
        }
        function propertyOf(object) {
          return function(path) {
            return object == null ? undefined$1 : baseGet(object, path);
          };
        }
        var range = createRange();
        var rangeRight = createRange(true);
        function stubArray() {
          return [];
        }
        function stubFalse() {
          return false;
        }
        function stubObject() {
          return {};
        }
        function stubString() {
          return "";
        }
        function stubTrue() {
          return true;
        }
        function times(n2, iteratee2) {
          n2 = toInteger(n2);
          if (n2 < 1 || n2 > MAX_SAFE_INTEGER) {
            return [];
          }
          var index2 = MAX_ARRAY_LENGTH, length = nativeMin(n2, MAX_ARRAY_LENGTH);
          iteratee2 = getIteratee(iteratee2);
          n2 -= MAX_ARRAY_LENGTH;
          var result2 = baseTimes(length, iteratee2);
          while (++index2 < n2) {
            iteratee2(index2);
          }
          return result2;
        }
        function toPath(value) {
          if (isArray(value)) {
            return arrayMap(value, toKey);
          }
          return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
        }
        function uniqueId(prefix) {
          var id = ++idCounter2;
          return toString(prefix) + id;
        }
        var add2 = createMathOperation(function(augend, addend) {
          return augend + addend;
        }, 0);
        var ceil = createRound("ceil");
        var divide = createMathOperation(function(dividend, divisor) {
          return dividend / divisor;
        }, 1);
        var floor = createRound("floor");
        function max(array) {
          return array && array.length ? baseExtremum(array, identity, baseGt) : undefined$1;
        }
        function maxBy(array, iteratee2) {
          return array && array.length ? baseExtremum(array, getIteratee(iteratee2, 2), baseGt) : undefined$1;
        }
        function mean(array) {
          return baseMean(array, identity);
        }
        function meanBy(array, iteratee2) {
          return baseMean(array, getIteratee(iteratee2, 2));
        }
        function min(array) {
          return array && array.length ? baseExtremum(array, identity, baseLt) : undefined$1;
        }
        function minBy(array, iteratee2) {
          return array && array.length ? baseExtremum(array, getIteratee(iteratee2, 2), baseLt) : undefined$1;
        }
        var multiply = createMathOperation(function(multiplier, multiplicand) {
          return multiplier * multiplicand;
        }, 1);
        var round = createRound("round");
        var subtract2 = createMathOperation(function(minuend, subtrahend) {
          return minuend - subtrahend;
        }, 0);
        function sum(array) {
          return array && array.length ? baseSum(array, identity) : 0;
        }
        function sumBy(array, iteratee2) {
          return array && array.length ? baseSum(array, getIteratee(iteratee2, 2)) : 0;
        }
        lodash2.after = after;
        lodash2.ary = ary;
        lodash2.assign = assign;
        lodash2.assignIn = assignIn;
        lodash2.assignInWith = assignInWith;
        lodash2.assignWith = assignWith;
        lodash2.at = at;
        lodash2.before = before;
        lodash2.bind = bind;
        lodash2.bindAll = bindAll;
        lodash2.bindKey = bindKey;
        lodash2.castArray = castArray;
        lodash2.chain = chain;
        lodash2.chunk = chunk;
        lodash2.compact = compact;
        lodash2.concat = concat;
        lodash2.cond = cond;
        lodash2.conforms = conforms;
        lodash2.constant = constant;
        lodash2.countBy = countBy;
        lodash2.create = create;
        lodash2.curry = curry;
        lodash2.curryRight = curryRight;
        lodash2.debounce = debounce;
        lodash2.defaults = defaults;
        lodash2.defaultsDeep = defaultsDeep;
        lodash2.defer = defer2;
        lodash2.delay = delay;
        lodash2.difference = difference;
        lodash2.differenceBy = differenceBy;
        lodash2.differenceWith = differenceWith;
        lodash2.drop = drop;
        lodash2.dropRight = dropRight;
        lodash2.dropRightWhile = dropRightWhile;
        lodash2.dropWhile = dropWhile;
        lodash2.fill = fill;
        lodash2.filter = filter;
        lodash2.flatMap = flatMap;
        lodash2.flatMapDeep = flatMapDeep;
        lodash2.flatMapDepth = flatMapDepth;
        lodash2.flatten = flatten;
        lodash2.flattenDeep = flattenDeep;
        lodash2.flattenDepth = flattenDepth;
        lodash2.flip = flip;
        lodash2.flow = flow;
        lodash2.flowRight = flowRight;
        lodash2.fromPairs = fromPairs;
        lodash2.functions = functions;
        lodash2.functionsIn = functionsIn;
        lodash2.groupBy = groupBy;
        lodash2.initial = initial;
        lodash2.intersection = intersection;
        lodash2.intersectionBy = intersectionBy;
        lodash2.intersectionWith = intersectionWith;
        lodash2.invert = invert;
        lodash2.invertBy = invertBy;
        lodash2.invokeMap = invokeMap;
        lodash2.iteratee = iteratee;
        lodash2.keyBy = keyBy;
        lodash2.keys = keys;
        lodash2.keysIn = keysIn;
        lodash2.map = map2;
        lodash2.mapKeys = mapKeys;
        lodash2.mapValues = mapValues;
        lodash2.matches = matches;
        lodash2.matchesProperty = matchesProperty;
        lodash2.memoize = memoize;
        lodash2.merge = merge;
        lodash2.mergeWith = mergeWith;
        lodash2.method = method;
        lodash2.methodOf = methodOf;
        lodash2.mixin = mixin;
        lodash2.negate = negate;
        lodash2.nthArg = nthArg;
        lodash2.omit = omit;
        lodash2.omitBy = omitBy;
        lodash2.once = once;
        lodash2.orderBy = orderBy;
        lodash2.over = over;
        lodash2.overArgs = overArgs;
        lodash2.overEvery = overEvery;
        lodash2.overSome = overSome;
        lodash2.partial = partial;
        lodash2.partialRight = partialRight;
        lodash2.partition = partition;
        lodash2.pick = pick;
        lodash2.pickBy = pickBy;
        lodash2.property = property;
        lodash2.propertyOf = propertyOf;
        lodash2.pull = pull;
        lodash2.pullAll = pullAll;
        lodash2.pullAllBy = pullAllBy;
        lodash2.pullAllWith = pullAllWith;
        lodash2.pullAt = pullAt;
        lodash2.range = range;
        lodash2.rangeRight = rangeRight;
        lodash2.rearg = rearg;
        lodash2.reject = reject;
        lodash2.remove = remove;
        lodash2.rest = rest;
        lodash2.reverse = reverse;
        lodash2.sampleSize = sampleSize;
        lodash2.set = set2;
        lodash2.setWith = setWith;
        lodash2.shuffle = shuffle;
        lodash2.slice = slice;
        lodash2.sortBy = sortBy;
        lodash2.sortedUniq = sortedUniq;
        lodash2.sortedUniqBy = sortedUniqBy;
        lodash2.split = split;
        lodash2.spread = spread;
        lodash2.tail = tail;
        lodash2.take = take;
        lodash2.takeRight = takeRight;
        lodash2.takeRightWhile = takeRightWhile;
        lodash2.takeWhile = takeWhile;
        lodash2.tap = tap;
        lodash2.throttle = throttle;
        lodash2.thru = thru;
        lodash2.toArray = toArray;
        lodash2.toPairs = toPairs;
        lodash2.toPairsIn = toPairsIn;
        lodash2.toPath = toPath;
        lodash2.toPlainObject = toPlainObject;
        lodash2.transform = transform;
        lodash2.unary = unary;
        lodash2.union = union;
        lodash2.unionBy = unionBy;
        lodash2.unionWith = unionWith;
        lodash2.uniq = uniq;
        lodash2.uniqBy = uniqBy;
        lodash2.uniqWith = uniqWith;
        lodash2.unset = unset;
        lodash2.unzip = unzip;
        lodash2.unzipWith = unzipWith;
        lodash2.update = update;
        lodash2.updateWith = updateWith;
        lodash2.values = values;
        lodash2.valuesIn = valuesIn;
        lodash2.without = without;
        lodash2.words = words;
        lodash2.wrap = wrap2;
        lodash2.xor = xor;
        lodash2.xorBy = xorBy;
        lodash2.xorWith = xorWith;
        lodash2.zip = zip;
        lodash2.zipObject = zipObject;
        lodash2.zipObjectDeep = zipObjectDeep;
        lodash2.zipWith = zipWith;
        lodash2.entries = toPairs;
        lodash2.entriesIn = toPairsIn;
        lodash2.extend = assignIn;
        lodash2.extendWith = assignInWith;
        mixin(lodash2, lodash2);
        lodash2.add = add2;
        lodash2.attempt = attempt;
        lodash2.camelCase = camelCase;
        lodash2.capitalize = capitalize2;
        lodash2.ceil = ceil;
        lodash2.clamp = clamp;
        lodash2.clone = clone;
        lodash2.cloneDeep = cloneDeep;
        lodash2.cloneDeepWith = cloneDeepWith;
        lodash2.cloneWith = cloneWith;
        lodash2.conformsTo = conformsTo;
        lodash2.deburr = deburr;
        lodash2.defaultTo = defaultTo;
        lodash2.divide = divide;
        lodash2.endsWith = endsWith;
        lodash2.eq = eq;
        lodash2.escape = escape2;
        lodash2.escapeRegExp = escapeRegExp;
        lodash2.every = every;
        lodash2.find = find;
        lodash2.findIndex = findIndex;
        lodash2.findKey = findKey;
        lodash2.findLast = findLast;
        lodash2.findLastIndex = findLastIndex;
        lodash2.findLastKey = findLastKey;
        lodash2.floor = floor;
        lodash2.forEach = forEach;
        lodash2.forEachRight = forEachRight;
        lodash2.forIn = forIn;
        lodash2.forInRight = forInRight;
        lodash2.forOwn = forOwn;
        lodash2.forOwnRight = forOwnRight;
        lodash2.get = get2;
        lodash2.gt = gt;
        lodash2.gte = gte;
        lodash2.has = has;
        lodash2.hasIn = hasIn;
        lodash2.head = head;
        lodash2.identity = identity;
        lodash2.includes = includes;
        lodash2.indexOf = indexOf;
        lodash2.inRange = inRange;
        lodash2.invoke = invoke;
        lodash2.isArguments = isArguments;
        lodash2.isArray = isArray;
        lodash2.isArrayBuffer = isArrayBuffer;
        lodash2.isArrayLike = isArrayLike;
        lodash2.isArrayLikeObject = isArrayLikeObject;
        lodash2.isBoolean = isBoolean;
        lodash2.isBuffer = isBuffer;
        lodash2.isDate = isDate;
        lodash2.isElement = isElement;
        lodash2.isEmpty = isEmpty2;
        lodash2.isEqual = isEqual;
        lodash2.isEqualWith = isEqualWith;
        lodash2.isError = isError;
        lodash2.isFinite = isFinite;
        lodash2.isFunction = isFunction;
        lodash2.isInteger = isInteger;
        lodash2.isLength = isLength;
        lodash2.isMap = isMap;
        lodash2.isMatch = isMatch;
        lodash2.isMatchWith = isMatchWith;
        lodash2.isNaN = isNaN2;
        lodash2.isNative = isNative;
        lodash2.isNil = isNil;
        lodash2.isNull = isNull;
        lodash2.isNumber = isNumber;
        lodash2.isObject = isObject2;
        lodash2.isObjectLike = isObjectLike;
        lodash2.isPlainObject = isPlainObject;
        lodash2.isRegExp = isRegExp;
        lodash2.isSafeInteger = isSafeInteger;
        lodash2.isSet = isSet;
        lodash2.isString = isString;
        lodash2.isSymbol = isSymbol;
        lodash2.isTypedArray = isTypedArray;
        lodash2.isUndefined = isUndefined;
        lodash2.isWeakMap = isWeakMap;
        lodash2.isWeakSet = isWeakSet;
        lodash2.join = join;
        lodash2.kebabCase = kebabCase;
        lodash2.last = last;
        lodash2.lastIndexOf = lastIndexOf;
        lodash2.lowerCase = lowerCase;
        lodash2.lowerFirst = lowerFirst;
        lodash2.lt = lt;
        lodash2.lte = lte;
        lodash2.max = max;
        lodash2.maxBy = maxBy;
        lodash2.mean = mean;
        lodash2.meanBy = meanBy;
        lodash2.min = min;
        lodash2.minBy = minBy;
        lodash2.stubArray = stubArray;
        lodash2.stubFalse = stubFalse;
        lodash2.stubObject = stubObject;
        lodash2.stubString = stubString;
        lodash2.stubTrue = stubTrue;
        lodash2.multiply = multiply;
        lodash2.nth = nth;
        lodash2.noConflict = noConflict;
        lodash2.noop = noop2;
        lodash2.now = now;
        lodash2.pad = pad;
        lodash2.padEnd = padEnd;
        lodash2.padStart = padStart;
        lodash2.parseInt = parseInt2;
        lodash2.random = random;
        lodash2.reduce = reduce;
        lodash2.reduceRight = reduceRight;
        lodash2.repeat = repeat;
        lodash2.replace = replace;
        lodash2.result = result;
        lodash2.round = round;
        lodash2.runInContext = runInContext2;
        lodash2.sample = sample;
        lodash2.size = size;
        lodash2.snakeCase = snakeCase;
        lodash2.some = some;
        lodash2.sortedIndex = sortedIndex;
        lodash2.sortedIndexBy = sortedIndexBy;
        lodash2.sortedIndexOf = sortedIndexOf;
        lodash2.sortedLastIndex = sortedLastIndex;
        lodash2.sortedLastIndexBy = sortedLastIndexBy;
        lodash2.sortedLastIndexOf = sortedLastIndexOf;
        lodash2.startCase = startCase;
        lodash2.startsWith = startsWith;
        lodash2.subtract = subtract2;
        lodash2.sum = sum;
        lodash2.sumBy = sumBy;
        lodash2.template = template;
        lodash2.times = times;
        lodash2.toFinite = toFinite;
        lodash2.toInteger = toInteger;
        lodash2.toLength = toLength;
        lodash2.toLower = toLower;
        lodash2.toNumber = toNumber;
        lodash2.toSafeInteger = toSafeInteger;
        lodash2.toString = toString;
        lodash2.toUpper = toUpper;
        lodash2.trim = trim;
        lodash2.trimEnd = trimEnd;
        lodash2.trimStart = trimStart;
        lodash2.truncate = truncate;
        lodash2.unescape = unescape2;
        lodash2.uniqueId = uniqueId;
        lodash2.upperCase = upperCase;
        lodash2.upperFirst = upperFirst;
        lodash2.each = forEach;
        lodash2.eachRight = forEachRight;
        lodash2.first = head;
        mixin(lodash2, function() {
          var source = {};
          baseForOwn(lodash2, function(func, methodName) {
            if (!hasOwnProperty.call(lodash2.prototype, methodName)) {
              source[methodName] = func;
            }
          });
          return source;
        }(), { "chain": false });
        lodash2.VERSION = VERSION;
        arrayEach(["bind", "bindKey", "curry", "curryRight", "partial", "partialRight"], function(methodName) {
          lodash2[methodName].placeholder = lodash2;
        });
        arrayEach(["drop", "take"], function(methodName, index2) {
          LazyWrapper.prototype[methodName] = function(n2) {
            n2 = n2 === undefined$1 ? 1 : nativeMax(toInteger(n2), 0);
            var result2 = this.__filtered__ && !index2 ? new LazyWrapper(this) : this.clone();
            if (result2.__filtered__) {
              result2.__takeCount__ = nativeMin(n2, result2.__takeCount__);
            } else {
              result2.__views__.push({
                "size": nativeMin(n2, MAX_ARRAY_LENGTH),
                "type": methodName + (result2.__dir__ < 0 ? "Right" : "")
              });
            }
            return result2;
          };
          LazyWrapper.prototype[methodName + "Right"] = function(n2) {
            return this.reverse()[methodName](n2).reverse();
          };
        });
        arrayEach(["filter", "map", "takeWhile"], function(methodName, index2) {
          var type = index2 + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;
          LazyWrapper.prototype[methodName] = function(iteratee2) {
            var result2 = this.clone();
            result2.__iteratees__.push({
              "iteratee": getIteratee(iteratee2, 3),
              "type": type
            });
            result2.__filtered__ = result2.__filtered__ || isFilter;
            return result2;
          };
        });
        arrayEach(["head", "last"], function(methodName, index2) {
          var takeName = "take" + (index2 ? "Right" : "");
          LazyWrapper.prototype[methodName] = function() {
            return this[takeName](1).value()[0];
          };
        });
        arrayEach(["initial", "tail"], function(methodName, index2) {
          var dropName = "drop" + (index2 ? "" : "Right");
          LazyWrapper.prototype[methodName] = function() {
            return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
          };
        });
        LazyWrapper.prototype.compact = function() {
          return this.filter(identity);
        };
        LazyWrapper.prototype.find = function(predicate) {
          return this.filter(predicate).head();
        };
        LazyWrapper.prototype.findLast = function(predicate) {
          return this.reverse().find(predicate);
        };
        LazyWrapper.prototype.invokeMap = baseRest(function(path, args) {
          if (typeof path == "function") {
            return new LazyWrapper(this);
          }
          return this.map(function(value) {
            return baseInvoke(value, path, args);
          });
        });
        LazyWrapper.prototype.reject = function(predicate) {
          return this.filter(negate(getIteratee(predicate)));
        };
        LazyWrapper.prototype.slice = function(start, end) {
          start = toInteger(start);
          var result2 = this;
          if (result2.__filtered__ && (start > 0 || end < 0)) {
            return new LazyWrapper(result2);
          }
          if (start < 0) {
            result2 = result2.takeRight(-start);
          } else if (start) {
            result2 = result2.drop(start);
          }
          if (end !== undefined$1) {
            end = toInteger(end);
            result2 = end < 0 ? result2.dropRight(-end) : result2.take(end - start);
          }
          return result2;
        };
        LazyWrapper.prototype.takeRightWhile = function(predicate) {
          return this.reverse().takeWhile(predicate).reverse();
        };
        LazyWrapper.prototype.toArray = function() {
          return this.take(MAX_ARRAY_LENGTH);
        };
        baseForOwn(LazyWrapper.prototype, function(func, methodName) {
          var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash2[isTaker ? "take" + (methodName == "last" ? "Right" : "") : methodName], retUnwrapped = isTaker || /^find/.test(methodName);
          if (!lodashFunc) {
            return;
          }
          lodash2.prototype[methodName] = function() {
            var value = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value instanceof LazyWrapper, iteratee2 = args[0], useLazy = isLazy || isArray(value);
            var interceptor = function(value2) {
              var result3 = lodashFunc.apply(lodash2, arrayPush([value2], args));
              return isTaker && chainAll ? result3[0] : result3;
            };
            if (useLazy && checkIteratee && typeof iteratee2 == "function" && iteratee2.length != 1) {
              isLazy = useLazy = false;
            }
            var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid;
            if (!retUnwrapped && useLazy) {
              value = onlyLazy ? value : new LazyWrapper(this);
              var result2 = func.apply(value, args);
              result2.__actions__.push({ "func": thru, "args": [interceptor], "thisArg": undefined$1 });
              return new LodashWrapper(result2, chainAll);
            }
            if (isUnwrapped && onlyLazy) {
              return func.apply(this, args);
            }
            result2 = this.thru(interceptor);
            return isUnwrapped ? isTaker ? result2.value()[0] : result2.value() : result2;
          };
        });
        arrayEach(["pop", "push", "shift", "sort", "splice", "unshift"], function(methodName) {
          var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? "tap" : "thru", retUnwrapped = /^(?:pop|shift)$/.test(methodName);
          lodash2.prototype[methodName] = function() {
            var args = arguments;
            if (retUnwrapped && !this.__chain__) {
              var value = this.value();
              return func.apply(isArray(value) ? value : [], args);
            }
            return this[chainName](function(value2) {
              return func.apply(isArray(value2) ? value2 : [], args);
            });
          };
        });
        baseForOwn(LazyWrapper.prototype, function(func, methodName) {
          var lodashFunc = lodash2[methodName];
          if (lodashFunc) {
            var key = lodashFunc.name + "";
            if (!hasOwnProperty.call(realNames, key)) {
              realNames[key] = [];
            }
            realNames[key].push({ "name": methodName, "func": lodashFunc });
          }
        });
        realNames[createHybrid(undefined$1, WRAP_BIND_KEY_FLAG).name] = [{
          "name": "wrapper",
          "func": undefined$1
        }];
        LazyWrapper.prototype.clone = lazyClone;
        LazyWrapper.prototype.reverse = lazyReverse;
        LazyWrapper.prototype.value = lazyValue;
        lodash2.prototype.at = wrapperAt;
        lodash2.prototype.chain = wrapperChain;
        lodash2.prototype.commit = wrapperCommit;
        lodash2.prototype.next = wrapperNext;
        lodash2.prototype.plant = wrapperPlant;
        lodash2.prototype.reverse = wrapperReverse;
        lodash2.prototype.toJSON = lodash2.prototype.valueOf = lodash2.prototype.value = wrapperValue;
        lodash2.prototype.first = lodash2.prototype.head;
        if (symIterator) {
          lodash2.prototype[symIterator] = wrapperToIterator;
        }
        return lodash2;
      };
      var _2 = runInContext();
      if (freeModule) {
        (freeModule.exports = _2)._ = _2;
        freeExports._ = _2;
      } else {
        root._ = _2;
      }
    }).call(commonjsGlobal);
  })(lodash, lodash.exports);
  var lodashExports = lodash.exports;
  const _ = /* @__PURE__ */ getDefaultExportFromCjs(lodashExports);
  const FirebaseSyncDialogue = () => {
    const alertContext = q$1(AlertContext);
    const firebaseContext = q$1(FirebaseContext);
    const settingsContext = q$1(SettingsContext);
    const sectionSelectionContext = q$1(SectionSelectionContext);
    function promptUpload({
      value,
      data,
      syncKey
    }) {
      alertContext.setOptions({
        title: instance.t(`${LANG_NS_SYNC}:alertUploadTitle`),
        text: instance.t(`${LANG_NS_SYNC}:alertUploadText`, {
          value
        }),
        okButtonText: instance.t(`${LANG_NS_MAIN}:yes`),
        cancelButtonText: instance.t(`${LANG_NS_MAIN}:no`),
        okCallback: () => {
          if (firebaseContext.db) {
            set(ref(firebaseContext.db, `${syncKey}/${VAL_FIREBASE_SYNC_SHARED_KEY}`), data);
          }
        },
        cancelCallback: () => {
          return;
        }
      });
      alertContext.setOpen();
    }
    function promptDownload({
      value,
      data,
      contextSetter
    }) {
      alertContext.setOptions({
        title: instance.t(`${LANG_NS_SYNC}:alertDownloadTitle`),
        text: instance.t(`${LANG_NS_SYNC}:alertDownloadText`, {
          value
        }),
        okButtonText: instance.t(`${LANG_NS_MAIN}:yes`),
        cancelButtonText: instance.t(`${LANG_NS_MAIN}:no`),
        okCallback: () => {
          contextSetter(data);
        },
        cancelCallback: () => {
          return;
        }
      });
      alertContext.setOpen();
    }
    const [localExercisesInformation, setLocalExercisesInformation] = h([]);
    const [syncedExercisesInformation, setSyncedExercisesInformation] = h([]);
    p(() => {
      const updatedIds = sectionSelectionContext.customSelectionsStorage.map(({
        exerciseID
      }) => exerciseID).filter((exerciseID, index2, array) => index2 === array.indexOf(exerciseID)).map((exerciseID) => {
        return {
          exerciseID,
          exerciseTitle: getTitleFromExerciseID({
            exerciseID,
            sectionSelectionContext
          })
        };
      });
      updatedIds.sort((a2, b2) => parseInt(a2.exerciseID) - parseInt(b2.exerciseID));
      setLocalExercisesInformation(updatedIds);
    }, [sectionSelectionContext.customSelectionsStorage, sectionSelectionContext.customSelectionsExercisesStorage]);
    p(() => {
      const updatedIds = firebaseContext.syncedSelectionsStorage.map(({
        exerciseID
      }) => exerciseID).filter((exerciseID, index2, array) => index2 === array.indexOf(exerciseID)).map((exerciseID) => {
        return {
          exerciseID,
          exerciseTitle: getTitleFromExerciseID({
            exerciseID,
            sectionSelectionContext
          })
        };
      });
      updatedIds.sort((a2, b2) => parseInt(a2.exerciseID) - parseInt(b2.exerciseID));
      setSyncedExercisesInformation(updatedIds);
    }, [firebaseContext.syncedExercisesStorage, firebaseContext.syncedSelectionsStorage]);
    const [sortedLocalExerciseStorage, setSortedLocalExerciseStorage] = h([]);
    const [sortedSyncedExerciseStorage, setSortedSyncedExerciseStorage] = h([]);
    p(() => {
      const sortedLocalExerciseStorage2 = sectionSelectionContext.customSelectionsExercisesStorage;
      sortedLocalExerciseStorage2.sort((a2, b2) => parseInt(a2.exerciseID) - parseInt(b2.exerciseID));
      setSortedLocalExerciseStorage(sortedLocalExerciseStorage2);
    }, [sectionSelectionContext.customSelectionsExercisesStorage]);
    p(() => {
      const sortedSyncedExerciseStorage2 = firebaseContext.syncedExercisesStorage;
      sortedSyncedExerciseStorage2.sort((a2, b2) => parseInt(a2.exerciseID) - parseInt(b2.exerciseID));
      setSortedSyncedExerciseStorage(sortedSyncedExerciseStorage2);
    }, [firebaseContext.syncedExercisesStorage]);
    const [noStatisticsLocalCustomSelections, setNoStatisticsLocalCustomSelections] = h([]);
    const [noStatisticsSyncedCustomSelections, setNoStatisticsSyncedCustomSelections] = h([]);
    const mapRemoveCustomSelectionStatistics = (props) => {
      const newProps = JSON.parse(JSON.stringify(props));
      delete newProps.lastPracticed;
      delete newProps.practicesToday;
      delete newProps.practicesTotal;
      return newProps;
    };
    p(() => {
      setNoStatisticsLocalCustomSelections(sectionSelectionContext.customSelectionsStorage.map(mapRemoveCustomSelectionStatistics));
    }, [sectionSelectionContext.customSelectionsStorage]);
    p(() => {
      setNoStatisticsSyncedCustomSelections(firebaseContext.syncedSelectionsStorage.map(mapRemoveCustomSelectionStatistics));
    }, [firebaseContext.syncedSelectionsStorage]);
    const getLanguageName = (languageCode) => {
      var _a2;
      return languageCode ? instance.t(`${LANG_NS_MAIN}:${(_a2 = getLanguageConfByCode(languageCode)) == null ? void 0 : _a2.i18nNameKey}`) : "-";
    };
    function onClickSettingsUploadButton() {
      var _a2;
      if (settingsContext.options.language && firebaseContext.syncedSettings.language !== settingsContext.options.language) {
        promptUpload({
          syncKey: VAL_FIREBASE_SYNC_SETTINGS_KEY,
          data: {
            language: settingsContext.options.language
          },
          value: instance.t(`${LANG_NS_MAIN}:${(_a2 = getLanguageConfByCode(settingsContext.options.language)) == null ? void 0 : _a2.i18nNameKey}`)
        });
      }
    }
    function onClickSettingDownloadButton() {
      var _a2;
      if (firebaseContext.syncedSettings.language && firebaseContext.syncedSettings.language !== settingsContext.options.language) {
        promptDownload({
          contextSetter: settingsContext.setOptions,
          data: {
            ...settingsContext.options,
            language: firebaseContext.syncedSettings.language
          },
          value: instance.t(`${LANG_NS_MAIN}:${(_a2 = getLanguageConfByCode(firebaseContext.syncedSettings.language)) == null ? void 0 : _a2.i18nNameKey}`)
        });
      }
    }
    function onClickExercisesUploadButton() {
      promptUpload({
        syncKey: VAL_FIREBASE_SYNC_CUSTOM_SELECTIONS_EXERCISES_STORAGE_KEY,
        data: sectionSelectionContext.customSelectionsExercisesStorage,
        value: instance.t(`${LANG_NS_MAIN}:wordalistExerciseInfo`, {
          count: sectionSelectionContext.customSelectionsExercisesStorage.length
        })
      });
    }
    function onClickExercisesDownloadButton() {
      promptDownload({
        contextSetter: sectionSelectionContext.setMultipleInCustomSelectionsExercisesStorage,
        data: {
          customSelectionsExercisesStorageSetters: firebaseContext.syncedExercisesStorage,
          resetStorage: true
        },
        value: instance.t(`${LANG_NS_MAIN}:wordalistExerciseInfo`, {
          count: firebaseContext.syncedSelectionsStorage.length
        })
      });
    }
    function onClickCustomSelectionsUploadButton() {
      if (sectionSelectionContext.customSelectionsStorage.length > 0 && !_.isEqual(noStatisticsLocalCustomSelections, noStatisticsSyncedCustomSelections)) {
        promptUpload({
          syncKey: VAL_FIREBASE_SYNC_CUSTOM_SELECTIONS_STORAGE_KEY,
          data: noStatisticsLocalCustomSelections,
          value: instance.t(`${LANG_NS_MAIN}:wordalistCustomSelection`, {
            count: sectionSelectionContext.customSelectionsStorage.length
          })
        });
      }
    }
    function onClickCustomSelectionsDownloadButton() {
      const updatedLocalStorage = firebaseContext.syncedSelectionsStorage.map((props) => {
        const localCustomSelection = getCustomSelectionFromHash({
          hash: props.hash,
          sectionSelectionContext
        });
        const localStatistics = {};
        if (localCustomSelection) {
          localStatistics.lastPracticed = localCustomSelection.lastPracticed;
          localStatistics.practicesToday = localCustomSelection.practicesToday;
          localStatistics.practicesTotal = localCustomSelection.practicesTotal;
        }
        return {
          ...props,
          ...localStatistics,
          exerciseTitle: getTitleFromExerciseID({
            exerciseID: props.exerciseID,
            sectionSelectionContext
          }),
          sections: props.sections.map(sectionsMapperRestoreElementIDs(props.exerciseID))
        };
      });
      promptDownload({
        contextSetter: sectionSelectionContext.setMultipleInCustomSelectionsStorage,
        data: {
          customSelectionsStorageSetters: updatedLocalStorage,
          resetStorage: true
        },
        value: instance.t(`${LANG_NS_MAIN}:wordalistCustomSelection`, {
          count: firebaseContext.syncedSelectionsStorage.length
        })
      });
    }
    return o($5d3850c4d0b4e6c7$export$be92b6f5f03c0fe9, {
      open: firebaseContext.dialogueOpen,
      children: o($5d3850c4d0b4e6c7$export$602eac185826482c, {
        children: [o($5d3850c4d0b4e6c7$export$c6fdb837b070b4ff, {
          className: "DialogOverlay"
        }), o($5d3850c4d0b4e6c7$export$7c6e2c02157bb7d2, {
          className: "DialogContent",
          children: [o($5d3850c4d0b4e6c7$export$f99233281efd08a0, {
            className: "DialogTitle",
            children: instance.t(`${LANG_NS_MAIN}:menuWLESynchronization`)
          }), o("div", {
            className: "DialogContentScroll",
            children: [o($5d3850c4d0b4e6c7$export$393edc798c47379d, {
              className: "DialogDescription",
              children: instance.t("sync:dialogueGeneralDescription")
            }), o("div", {
              className: "MultiFieldset",
              children: [o("div", {
                className: "FieldsetTitle",
                children: instance.t(`${LANG_NS_SYNC}:dialogueSectionSettingsLanguageTitle`)
              }), o("fieldset", {
                className: "Fieldset",
                children: [o("label", {
                  className: "Label",
                  children: instance.t(`${LANG_NS_SYNC}:dialogueSectionSettingsLanguageLocal`)
                }), o("input", {
                  className: "Input",
                  readOnly: true,
                  value: getLanguageName(settingsContext.options.language)
                }), o("button", {
                  className: "Button green",
                  disabled: firebaseContext.syncedSettings.language === settingsContext.options.language,
                  onClick: onClickSettingsUploadButton,
                  children: o(UploadIcon, {})
                })]
              }), o("fieldset", {
                className: "Fieldset",
                children: [o("label", {
                  className: "Label",
                  children: instance.t(`${LANG_NS_SYNC}:dialogueSectionSettingsLanguageSync`)
                }), o("input", {
                  className: "Input",
                  readOnly: true,
                  value: getLanguageName(firebaseContext.syncedSettings.language)
                }), o("button", {
                  className: "Button blue",
                  disabled: firebaseContext.syncedSettings.language === settingsContext.options.language,
                  onClick: onClickSettingDownloadButton,
                  children: o(DownloadIcon, {})
                })]
              })]
            }), o("div", {
              className: "MultiFieldset",
              children: [o("div", {
                className: "FieldsetTitle",
                children: instance.t(`${LANG_NS_SYNC}:dialogueSectionSelectionsExercisesTitle`)
              }), o("fieldset", {
                className: "Fieldset",
                children: [o("label", {
                  className: "Label",
                  children: instance.t(`${LANG_NS_SYNC}:dialogueSectionSelectionsExercisesLocal`)
                }), o("ul", {
                  className: "SyncExercisesList",
                  children: sortedLocalExerciseStorage.length > 0 && sortedLocalExerciseStorage.map(({
                    exerciseID,
                    exerciseTitle
                  }) => {
                    var _a2, _b;
                    return o("li", {
                      style: {
                        textAlign: "left"
                      },
                      children: [instance.t(`${LANG_NS_MAIN}:wordalistExercise`, {
                        id: exerciseID
                      }), ": ", o("span", {
                        className: `SyncExerciseName ${exerciseTitle !== ((_b = (_a2 = firebaseContext.syncedExercisesStorage.filter(propFilterExerciseID(exerciseID))) == null ? void 0 : _a2[0]) == null ? void 0 : _b.exerciseTitle) ? " SyncExerciseNameDiffer" : ""}`,
                        children: exerciseTitle
                      })]
                    });
                  }) || o("li", {
                    children: " - "
                  })
                }), o("button", {
                  className: "Button green",
                  disabled: sortedLocalExerciseStorage.length === 0 || _.isEqual(sortedSyncedExerciseStorage, sortedLocalExerciseStorage),
                  onClick: onClickExercisesUploadButton,
                  children: o(UploadIcon, {})
                })]
              }), o("fieldset", {
                className: "Fieldset",
                children: [o("label", {
                  className: "Label",
                  children: instance.t(`${LANG_NS_SYNC}:dialogueSectionSelectionsExercisesSync`)
                }), o("ul", {
                  className: "SyncExercisesList",
                  children: firebaseContext.syncedExercisesStorage.length > 0 && sortedSyncedExerciseStorage.map(({
                    exerciseID,
                    exerciseTitle
                  }) => {
                    var _a2, _b;
                    return o("li", {
                      style: {
                        textAlign: "left"
                      },
                      children: [instance.t(`${LANG_NS_MAIN}:wordalistExercise`, {
                        id: exerciseID
                      }), ": ", o("span", {
                        className: `SyncExerciseName ${exerciseTitle !== ((_b = (_a2 = sectionSelectionContext.customSelectionsExercisesStorage.filter(propFilterExerciseID(exerciseID))) == null ? void 0 : _a2[0]) == null ? void 0 : _b.exerciseTitle) ? " SyncExerciseNameDiffer" : ""}`,
                        children: exerciseTitle
                      })]
                    });
                  }) || o("li", {
                    children: "-"
                  })
                }), o("button", {
                  className: "Button blue",
                  disabled: firebaseContext.syncedExercisesStorage.length === 0 || _.isEqual(sortedSyncedExerciseStorage, sortedLocalExerciseStorage),
                  onClick: onClickExercisesDownloadButton,
                  children: o(DownloadIcon, {})
                })]
              })]
            }), o("div", {
              className: "MultiFieldset",
              children: [o("div", {
                className: "FieldsetTitle",
                children: instance.t(`${LANG_NS_SYNC}:dialogueSectionSelectionsCustomSelectionsTitle`)
              }), o("fieldset", {
                className: "Fieldset",
                children: [o("label", {
                  className: "Label",
                  children: instance.t(`${LANG_NS_SYNC}:dialogueSectionSelectionsCustomSelectionsLocal`)
                }), o("ul", {
                  className: "SyncExercisesList",
                  children: localExercisesInformation.map(({
                    exerciseID,
                    exerciseTitle
                  }) => {
                    var _a2, _b;
                    return o("li", {
                      children: [o("span", {
                        className: exerciseTitle !== ((_b = (_a2 = firebaseContext.syncedExercisesStorage.filter(propFilterExerciseID(exerciseID))) == null ? void 0 : _a2[0]) == null ? void 0 : _b.exerciseTitle) ? "SyncExerciseNameDiffer" : "",
                        children: [exerciseTitle, " (", exerciseID, ")"]
                      }), o("ul", {
                        className: "SyncSectionsList",
                        children: sectionSelectionContext.customSelectionsStorage.filter(propFilterExerciseID(exerciseID)).map(({
                          name: name2,
                          hash,
                          sections
                        }) => {
                          var _a3, _b2;
                          return o("li", {
                            children: o("span", {
                              className: hash !== ((_b2 = (_a3 = firebaseContext.syncedSelectionsStorage.filter(propFilterCustomSelectionHash(hash))) == null ? void 0 : _a3[0]) == null ? void 0 : _b2.hash) ? "SyncExerciseNameDiffer" : "",
                              children: [name2, " (", instance.t(`${LANG_NS_MAIN}:wordalistSection`, {
                                count: sections.length
                              }), ")"]
                            })
                          });
                        })
                      })]
                    });
                  })
                }), o("button", {
                  className: "Button green",
                  disabled: sectionSelectionContext.customSelectionsStorage.length === 0 || _.isEqual(noStatisticsLocalCustomSelections, noStatisticsSyncedCustomSelections),
                  onClick: onClickCustomSelectionsUploadButton,
                  children: o(UploadIcon, {})
                })]
              }), o("fieldset", {
                className: "Fieldset",
                children: [o("label", {
                  className: "Label",
                  children: instance.t(`${LANG_NS_SYNC}:dialogueSectionSelectionsCustomSelectionsSync`)
                }), o("ul", {
                  className: "SyncExercisesList",
                  children: syncedExercisesInformation.length > 0 && syncedExercisesInformation.map(({
                    exerciseID,
                    exerciseTitle
                  }) => {
                    var _a2, _b;
                    return o("li", {
                      children: [o("span", {
                        className: exerciseTitle !== ((_b = (_a2 = sectionSelectionContext.customSelectionsExercisesStorage.filter(propFilterExerciseID(exerciseID))) == null ? void 0 : _a2[0]) == null ? void 0 : _b.exerciseTitle) ? "SyncExerciseNameDiffer" : "",
                        children: [exerciseTitle, " (", exerciseID, ")"]
                      }), o("ul", {
                        className: "SyncSectionsList",
                        children: firebaseContext.syncedSelectionsStorage.filter(propFilterExerciseID(exerciseID)).map(({
                          name: name2,
                          hash,
                          sections
                        }) => {
                          var _a3, _b2;
                          return o("li", {
                            children: o("span", {
                              className: hash !== ((_b2 = (_a3 = sectionSelectionContext.customSelectionsStorage.filter(propFilterCustomSelectionHash(hash))) == null ? void 0 : _a3[0]) == null ? void 0 : _b2.hash) ? "SyncExerciseNameDiffer" : "",
                              children: [name2, " (", instance.t(`${LANG_NS_MAIN}:wordalistSection`, {
                                count: sections.length
                              }), ")"]
                            })
                          });
                        })
                      })]
                    });
                  }) || o("li", {
                    children: "-"
                  })
                }), o("button", {
                  className: "Button blue",
                  disabled: firebaseContext.syncedSelectionsStorage.length === 0 || _.isEqual(noStatisticsLocalCustomSelections, noStatisticsSyncedCustomSelections),
                  onClick: onClickCustomSelectionsDownloadButton,
                  children: o(DownloadIcon, {})
                })]
              })]
            })]
          }), o("button", {
            className: "IconButton",
            "aria-label": "Close",
            onClick: firebaseContext.closeDialogue,
            children: o(Cross2Icon, {})
          })]
        })]
      })
    });
  };
  const $ea1ef594cf570d83$export$439d29a4e110a164 = /* @__PURE__ */ k((props, forwardedRef) => {
    return /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.span, _extends({}, props, {
      ref: forwardedRef,
      style: {
        // See: https://github.com/twbs/bootstrap/blob/master/scss/mixins/_screen-reader.scss
        position: "absolute",
        border: 0,
        width: 1,
        height: 1,
        padding: 0,
        margin: -1,
        overflow: "hidden",
        clip: "rect(0, 0, 0, 0)",
        whiteSpace: "nowrap",
        wordWrap: "normal",
        ...props.style
      }
    }));
  });
  const $054eb8030ebde76e$var$PROVIDER_NAME = "ToastProvider";
  const [$054eb8030ebde76e$var$Collection, $054eb8030ebde76e$var$useCollection, $054eb8030ebde76e$var$createCollectionScope] = $e02a7d9cb1dc128c$export$c74125a8e3af6bb2("Toast");
  const [$054eb8030ebde76e$var$createToastContext, $054eb8030ebde76e$export$8a359da18fbc9073] = $c512c27ab02ef895$export$50c7b4e9d9f19c1("Toast", [
    $054eb8030ebde76e$var$createCollectionScope
  ]);
  const [$054eb8030ebde76e$var$ToastProviderProvider, $054eb8030ebde76e$var$useToastProviderContext] = $054eb8030ebde76e$var$createToastContext($054eb8030ebde76e$var$PROVIDER_NAME);
  const $054eb8030ebde76e$export$f5d03d415824e0e = (props) => {
    const { __scopeToast, label = "Notification", duration = 5e3, swipeDirection = "right", swipeThreshold = 50, children } = props;
    const [viewport, setViewport] = h(null);
    const [toastCount, setToastCount] = h(0);
    const isFocusedToastEscapeKeyDownRef = _$2(false);
    const isClosePausedRef = _$2(false);
    return /* @__PURE__ */ y$1($054eb8030ebde76e$var$Collection.Provider, {
      scope: __scopeToast
    }, /* @__PURE__ */ y$1($054eb8030ebde76e$var$ToastProviderProvider, {
      scope: __scopeToast,
      label,
      duration,
      swipeDirection,
      swipeThreshold,
      toastCount,
      viewport,
      onViewportChange: setViewport,
      onToastAdd: T$1(
        () => setToastCount(
          (prevCount) => prevCount + 1
        ),
        []
      ),
      onToastRemove: T$1(
        () => setToastCount(
          (prevCount) => prevCount - 1
        ),
        []
      ),
      isFocusedToastEscapeKeyDownRef,
      isClosePausedRef
    }, children));
  };
  $054eb8030ebde76e$export$f5d03d415824e0e.propTypes = {
    label(props) {
      if (props.label && typeof props.label === "string" && !props.label.trim()) {
        const error2 = `Invalid prop \`label\` supplied to \`${$054eb8030ebde76e$var$PROVIDER_NAME}\`. Expected non-empty \`string\`.`;
        return new Error(error2);
      }
      return null;
    }
  };
  const $054eb8030ebde76e$var$VIEWPORT_NAME = "ToastViewport";
  const $054eb8030ebde76e$var$VIEWPORT_DEFAULT_HOTKEY = [
    "F8"
  ];
  const $054eb8030ebde76e$var$VIEWPORT_PAUSE = "toast.viewportPause";
  const $054eb8030ebde76e$var$VIEWPORT_RESUME = "toast.viewportResume";
  const $054eb8030ebde76e$export$6192c2425ecfd989 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeToast, hotkey = $054eb8030ebde76e$var$VIEWPORT_DEFAULT_HOTKEY, label = "Notifications ({hotkey})", ...viewportProps } = props;
    const context = $054eb8030ebde76e$var$useToastProviderContext($054eb8030ebde76e$var$VIEWPORT_NAME, __scopeToast);
    const getItems = $054eb8030ebde76e$var$useCollection(__scopeToast);
    const wrapperRef = _$2(null);
    const headFocusProxyRef = _$2(null);
    const tailFocusProxyRef = _$2(null);
    const ref2 = _$2(null);
    const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref2, context.onViewportChange);
    const hotkeyLabel = hotkey.join("+").replace(/Key/g, "").replace(/Digit/g, "");
    const hasToasts = context.toastCount > 0;
    p(() => {
      const handleKeyDown = (event) => {
        var _ref$current;
        const isHotkeyPressed = hotkey.every(
          (key) => event[key] || event.code === key
        );
        if (isHotkeyPressed)
          (_ref$current = ref2.current) === null || _ref$current === void 0 || _ref$current.focus();
      };
      document.addEventListener("keydown", handleKeyDown);
      return () => document.removeEventListener("keydown", handleKeyDown);
    }, [
      hotkey
    ]);
    p(() => {
      const wrapper = wrapperRef.current;
      const viewport = ref2.current;
      if (hasToasts && wrapper && viewport) {
        const handlePause = () => {
          if (!context.isClosePausedRef.current) {
            const pauseEvent = new CustomEvent($054eb8030ebde76e$var$VIEWPORT_PAUSE);
            viewport.dispatchEvent(pauseEvent);
            context.isClosePausedRef.current = true;
          }
        };
        const handleResume = () => {
          if (context.isClosePausedRef.current) {
            const resumeEvent = new CustomEvent($054eb8030ebde76e$var$VIEWPORT_RESUME);
            viewport.dispatchEvent(resumeEvent);
            context.isClosePausedRef.current = false;
          }
        };
        const handleFocusOutResume = (event) => {
          const isFocusMovingOutside = !wrapper.contains(event.relatedTarget);
          if (isFocusMovingOutside)
            handleResume();
        };
        const handlePointerLeaveResume = () => {
          const isFocusInside = wrapper.contains(document.activeElement);
          if (!isFocusInside)
            handleResume();
        };
        wrapper.addEventListener("focusin", handlePause);
        wrapper.addEventListener("focusout", handleFocusOutResume);
        wrapper.addEventListener("pointermove", handlePause);
        wrapper.addEventListener("pointerleave", handlePointerLeaveResume);
        window.addEventListener("blur", handlePause);
        window.addEventListener("focus", handleResume);
        return () => {
          wrapper.removeEventListener("focusin", handlePause);
          wrapper.removeEventListener("focusout", handleFocusOutResume);
          wrapper.removeEventListener("pointermove", handlePause);
          wrapper.removeEventListener("pointerleave", handlePointerLeaveResume);
          window.removeEventListener("blur", handlePause);
          window.removeEventListener("focus", handleResume);
        };
      }
    }, [
      hasToasts,
      context.isClosePausedRef
    ]);
    const getSortedTabbableCandidates = T$1(({ tabbingDirection }) => {
      const toastItems = getItems();
      const tabbableCandidates = toastItems.map((toastItem) => {
        const toastNode = toastItem.ref.current;
        const toastTabbableCandidates = [
          toastNode,
          ...$054eb8030ebde76e$var$getTabbableCandidates(toastNode)
        ];
        return tabbingDirection === "forwards" ? toastTabbableCandidates : toastTabbableCandidates.reverse();
      });
      return (tabbingDirection === "forwards" ? tabbableCandidates.reverse() : tabbableCandidates).flat();
    }, [
      getItems
    ]);
    p(() => {
      const viewport = ref2.current;
      if (viewport) {
        const handleKeyDown = (event) => {
          const isMetaKey = event.altKey || event.ctrlKey || event.metaKey;
          const isTabKey = event.key === "Tab" && !isMetaKey;
          if (isTabKey) {
            const focusedElement = document.activeElement;
            const isTabbingBackwards = event.shiftKey;
            const targetIsViewport = event.target === viewport;
            if (targetIsViewport && isTabbingBackwards) {
              var _headFocusProxyRef$cu;
              (_headFocusProxyRef$cu = headFocusProxyRef.current) === null || _headFocusProxyRef$cu === void 0 || _headFocusProxyRef$cu.focus();
              return;
            }
            const tabbingDirection = isTabbingBackwards ? "backwards" : "forwards";
            const sortedCandidates = getSortedTabbableCandidates({
              tabbingDirection
            });
            const index2 = sortedCandidates.findIndex(
              (candidate) => candidate === focusedElement
            );
            if ($054eb8030ebde76e$var$focusFirst(sortedCandidates.slice(index2 + 1)))
              event.preventDefault();
            else {
              var _headFocusProxyRef$cu2, _tailFocusProxyRef$cu;
              isTabbingBackwards ? (_headFocusProxyRef$cu2 = headFocusProxyRef.current) === null || _headFocusProxyRef$cu2 === void 0 || _headFocusProxyRef$cu2.focus() : (_tailFocusProxyRef$cu = tailFocusProxyRef.current) === null || _tailFocusProxyRef$cu === void 0 || _tailFocusProxyRef$cu.focus();
            }
          }
        };
        viewport.addEventListener("keydown", handleKeyDown);
        return () => viewport.removeEventListener("keydown", handleKeyDown);
      }
    }, [
      getItems,
      getSortedTabbableCandidates
    ]);
    return /* @__PURE__ */ y$1($5cb92bef7577960e$export$aecb2ddcb55c95be, {
      ref: wrapperRef,
      role: "region",
      "aria-label": label.replace("{hotkey}", hotkeyLabel),
      tabIndex: -1,
      style: {
        pointerEvents: hasToasts ? void 0 : "none"
      }
    }, hasToasts && /* @__PURE__ */ y$1($054eb8030ebde76e$var$FocusProxy, {
      ref: headFocusProxyRef,
      onFocusFromOutsideViewport: () => {
        const tabbableCandidates = getSortedTabbableCandidates({
          tabbingDirection: "forwards"
        });
        $054eb8030ebde76e$var$focusFirst(tabbableCandidates);
      }
    }), /* @__PURE__ */ y$1($054eb8030ebde76e$var$Collection.Slot, {
      scope: __scopeToast
    }, /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.ol, _extends({
      tabIndex: -1
    }, viewportProps, {
      ref: composedRefs
    }))), hasToasts && /* @__PURE__ */ y$1($054eb8030ebde76e$var$FocusProxy, {
      ref: tailFocusProxyRef,
      onFocusFromOutsideViewport: () => {
        const tabbableCandidates = getSortedTabbableCandidates({
          tabbingDirection: "backwards"
        });
        $054eb8030ebde76e$var$focusFirst(tabbableCandidates);
      }
    }));
  });
  const $054eb8030ebde76e$var$FOCUS_PROXY_NAME = "ToastFocusProxy";
  const $054eb8030ebde76e$var$FocusProxy = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeToast, onFocusFromOutsideViewport, ...proxyProps } = props;
    const context = $054eb8030ebde76e$var$useToastProviderContext($054eb8030ebde76e$var$FOCUS_PROXY_NAME, __scopeToast);
    return /* @__PURE__ */ y$1($ea1ef594cf570d83$export$439d29a4e110a164, _extends({
      "aria-hidden": true,
      tabIndex: 0
    }, proxyProps, {
      ref: forwardedRef,
      style: {
        position: "fixed"
      },
      onFocus: (event) => {
        var _context$viewport;
        const prevFocusedElement = event.relatedTarget;
        const isFocusFromOutsideViewport = !((_context$viewport = context.viewport) !== null && _context$viewport !== void 0 && _context$viewport.contains(prevFocusedElement));
        if (isFocusFromOutsideViewport)
          onFocusFromOutsideViewport();
      }
    }));
  });
  const $054eb8030ebde76e$var$TOAST_NAME = "Toast";
  const $054eb8030ebde76e$var$TOAST_SWIPE_START = "toast.swipeStart";
  const $054eb8030ebde76e$var$TOAST_SWIPE_MOVE = "toast.swipeMove";
  const $054eb8030ebde76e$var$TOAST_SWIPE_CANCEL = "toast.swipeCancel";
  const $054eb8030ebde76e$var$TOAST_SWIPE_END = "toast.swipeEnd";
  const $054eb8030ebde76e$export$8d8dc7d5f743331b = /* @__PURE__ */ k((props, forwardedRef) => {
    const { forceMount, open: openProp, defaultOpen, onOpenChange, ...toastProps } = props;
    const [open = true, setOpen] = $71cd76cc60e0454e$export$6f32135080cb4c3({
      prop: openProp,
      defaultProp: defaultOpen,
      onChange: onOpenChange
    });
    return /* @__PURE__ */ y$1($921a889cee6df7e8$export$99c2b779aa4e8b8b, {
      present: forceMount || open
    }, /* @__PURE__ */ y$1($054eb8030ebde76e$var$ToastImpl, _extends({
      open
    }, toastProps, {
      ref: forwardedRef,
      onClose: () => setOpen(false),
      onPause: $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(props.onPause),
      onResume: $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(props.onResume),
      onSwipeStart: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onSwipeStart, (event) => {
        event.currentTarget.setAttribute("data-swipe", "start");
      }),
      onSwipeMove: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onSwipeMove, (event) => {
        const { x: x2, y: y2 } = event.detail.delta;
        event.currentTarget.setAttribute("data-swipe", "move");
        event.currentTarget.style.setProperty("--radix-toast-swipe-move-x", `${x2}px`);
        event.currentTarget.style.setProperty("--radix-toast-swipe-move-y", `${y2}px`);
      }),
      onSwipeCancel: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onSwipeCancel, (event) => {
        event.currentTarget.setAttribute("data-swipe", "cancel");
        event.currentTarget.style.removeProperty("--radix-toast-swipe-move-x");
        event.currentTarget.style.removeProperty("--radix-toast-swipe-move-y");
        event.currentTarget.style.removeProperty("--radix-toast-swipe-end-x");
        event.currentTarget.style.removeProperty("--radix-toast-swipe-end-y");
      }),
      onSwipeEnd: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onSwipeEnd, (event) => {
        const { x: x2, y: y2 } = event.detail.delta;
        event.currentTarget.setAttribute("data-swipe", "end");
        event.currentTarget.style.removeProperty("--radix-toast-swipe-move-x");
        event.currentTarget.style.removeProperty("--radix-toast-swipe-move-y");
        event.currentTarget.style.setProperty("--radix-toast-swipe-end-x", `${x2}px`);
        event.currentTarget.style.setProperty("--radix-toast-swipe-end-y", `${y2}px`);
        setOpen(false);
      })
    })));
  });
  const [$054eb8030ebde76e$var$ToastInteractiveProvider, $054eb8030ebde76e$var$useToastInteractiveContext] = $054eb8030ebde76e$var$createToastContext($054eb8030ebde76e$var$TOAST_NAME, {
    onClose() {
    }
  });
  const $054eb8030ebde76e$var$ToastImpl = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeToast, type = "foreground", duration: durationProp, open, onClose, onEscapeKeyDown, onPause, onResume, onSwipeStart, onSwipeMove, onSwipeCancel, onSwipeEnd, ...toastProps } = props;
    const context = $054eb8030ebde76e$var$useToastProviderContext($054eb8030ebde76e$var$TOAST_NAME, __scopeToast);
    const [node1, setNode] = h(null);
    const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(
      forwardedRef,
      (node) => setNode(node)
    );
    const pointerStartRef = _$2(null);
    const swipeDeltaRef = _$2(null);
    const duration1 = durationProp || context.duration;
    const closeTimerStartTimeRef = _$2(0);
    const closeTimerRemainingTimeRef = _$2(duration1);
    const closeTimerRef = _$2(0);
    const { onToastAdd, onToastRemove } = context;
    const handleClose = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(() => {
      var _context$viewport2;
      const isFocusInToast = node1 === null || node1 === void 0 ? void 0 : node1.contains(document.activeElement);
      if (isFocusInToast)
        (_context$viewport2 = context.viewport) === null || _context$viewport2 === void 0 || _context$viewport2.focus();
      onClose();
    });
    const startTimer = T$1((duration) => {
      if (!duration || duration === Infinity)
        return;
      window.clearTimeout(closeTimerRef.current);
      closeTimerStartTimeRef.current = (/* @__PURE__ */ new Date()).getTime();
      closeTimerRef.current = window.setTimeout(handleClose, duration);
    }, [
      handleClose
    ]);
    p(() => {
      const viewport = context.viewport;
      if (viewport) {
        const handleResume = () => {
          startTimer(closeTimerRemainingTimeRef.current);
          onResume === null || onResume === void 0 || onResume();
        };
        const handlePause = () => {
          const elapsedTime = (/* @__PURE__ */ new Date()).getTime() - closeTimerStartTimeRef.current;
          closeTimerRemainingTimeRef.current = closeTimerRemainingTimeRef.current - elapsedTime;
          window.clearTimeout(closeTimerRef.current);
          onPause === null || onPause === void 0 || onPause();
        };
        viewport.addEventListener($054eb8030ebde76e$var$VIEWPORT_PAUSE, handlePause);
        viewport.addEventListener($054eb8030ebde76e$var$VIEWPORT_RESUME, handleResume);
        return () => {
          viewport.removeEventListener($054eb8030ebde76e$var$VIEWPORT_PAUSE, handlePause);
          viewport.removeEventListener($054eb8030ebde76e$var$VIEWPORT_RESUME, handleResume);
        };
      }
    }, [
      context.viewport,
      duration1,
      onPause,
      onResume,
      startTimer
    ]);
    p(() => {
      if (open && !context.isClosePausedRef.current)
        startTimer(duration1);
    }, [
      open,
      duration1,
      context.isClosePausedRef,
      startTimer
    ]);
    p(() => {
      onToastAdd();
      return () => onToastRemove();
    }, [
      onToastAdd,
      onToastRemove
    ]);
    const announceTextContent = F$1(() => {
      return node1 ? $054eb8030ebde76e$var$getAnnounceTextContent(node1) : null;
    }, [
      node1
    ]);
    if (!context.viewport)
      return null;
    return /* @__PURE__ */ y$1(k$2, null, announceTextContent && /* @__PURE__ */ y$1($054eb8030ebde76e$var$ToastAnnounce, {
      __scopeToast,
      role: "status",
      "aria-live": type === "foreground" ? "assertive" : "polite",
      "aria-atomic": true
    }, announceTextContent), /* @__PURE__ */ y$1($054eb8030ebde76e$var$ToastInteractiveProvider, {
      scope: __scopeToast,
      onClose: handleClose
    }, /* @__PURE__ */ z(/* @__PURE__ */ y$1($054eb8030ebde76e$var$Collection.ItemSlot, {
      scope: __scopeToast
    }, /* @__PURE__ */ y$1($5cb92bef7577960e$export$be92b6f5f03c0fe9, {
      asChild: true,
      onEscapeKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(onEscapeKeyDown, () => {
        if (!context.isFocusedToastEscapeKeyDownRef.current)
          handleClose();
        context.isFocusedToastEscapeKeyDownRef.current = false;
      })
    }, /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.li, _extends({
      // Ensure toasts are announced as status list or status when focused
      role: "status",
      "aria-live": "off",
      "aria-atomic": true,
      tabIndex: 0,
      "data-state": open ? "open" : "closed",
      "data-swipe-direction": context.swipeDirection
    }, toastProps, {
      ref: composedRefs,
      style: {
        userSelect: "none",
        touchAction: "none",
        ...props.style
      },
      onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onKeyDown, (event) => {
        if (event.key !== "Escape")
          return;
        onEscapeKeyDown === null || onEscapeKeyDown === void 0 || onEscapeKeyDown(event.nativeEvent);
        if (!event.nativeEvent.defaultPrevented) {
          context.isFocusedToastEscapeKeyDownRef.current = true;
          handleClose();
        }
      }),
      onPointerDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerDown, (event) => {
        if (event.button !== 0)
          return;
        pointerStartRef.current = {
          x: event.clientX,
          y: event.clientY
        };
      }),
      onPointerMove: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerMove, (event) => {
        if (!pointerStartRef.current)
          return;
        const x2 = event.clientX - pointerStartRef.current.x;
        const y2 = event.clientY - pointerStartRef.current.y;
        const hasSwipeMoveStarted = Boolean(swipeDeltaRef.current);
        const isHorizontalSwipe = [
          "left",
          "right"
        ].includes(context.swipeDirection);
        const clamp = [
          "left",
          "up"
        ].includes(context.swipeDirection) ? Math.min : Math.max;
        const clampedX = isHorizontalSwipe ? clamp(0, x2) : 0;
        const clampedY = !isHorizontalSwipe ? clamp(0, y2) : 0;
        const moveStartBuffer = event.pointerType === "touch" ? 10 : 2;
        const delta = {
          x: clampedX,
          y: clampedY
        };
        const eventDetail = {
          originalEvent: event,
          delta
        };
        if (hasSwipeMoveStarted) {
          swipeDeltaRef.current = delta;
          $054eb8030ebde76e$var$handleAndDispatchCustomEvent($054eb8030ebde76e$var$TOAST_SWIPE_MOVE, onSwipeMove, eventDetail, {
            discrete: false
          });
        } else if ($054eb8030ebde76e$var$isDeltaInDirection(delta, context.swipeDirection, moveStartBuffer)) {
          swipeDeltaRef.current = delta;
          $054eb8030ebde76e$var$handleAndDispatchCustomEvent($054eb8030ebde76e$var$TOAST_SWIPE_START, onSwipeStart, eventDetail, {
            discrete: false
          });
          event.target.setPointerCapture(event.pointerId);
        } else if (Math.abs(x2) > moveStartBuffer || Math.abs(y2) > moveStartBuffer)
          pointerStartRef.current = null;
      }),
      onPointerUp: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onPointerUp, (event1) => {
        const delta = swipeDeltaRef.current;
        const target = event1.target;
        if (target.hasPointerCapture(event1.pointerId))
          target.releasePointerCapture(event1.pointerId);
        swipeDeltaRef.current = null;
        pointerStartRef.current = null;
        if (delta) {
          const toast = event1.currentTarget;
          const eventDetail = {
            originalEvent: event1,
            delta
          };
          if ($054eb8030ebde76e$var$isDeltaInDirection(delta, context.swipeDirection, context.swipeThreshold))
            $054eb8030ebde76e$var$handleAndDispatchCustomEvent($054eb8030ebde76e$var$TOAST_SWIPE_END, onSwipeEnd, eventDetail, {
              discrete: true
            });
          else
            $054eb8030ebde76e$var$handleAndDispatchCustomEvent($054eb8030ebde76e$var$TOAST_SWIPE_CANCEL, onSwipeCancel, eventDetail, {
              discrete: true
            });
          toast.addEventListener(
            "click",
            (event) => event.preventDefault(),
            {
              once: true
            }
          );
        }
      })
    })))), context.viewport)));
  });
  $054eb8030ebde76e$var$ToastImpl.propTypes = {
    type(props) {
      if (props.type && ![
        "foreground",
        "background"
      ].includes(props.type)) {
        const error2 = `Invalid prop \`type\` supplied to \`${$054eb8030ebde76e$var$TOAST_NAME}\`. Expected \`foreground | background\`.`;
        return new Error(error2);
      }
      return null;
    }
  };
  const $054eb8030ebde76e$var$ToastAnnounce = (props) => {
    const { __scopeToast, children, ...announceProps } = props;
    const context = $054eb8030ebde76e$var$useToastProviderContext($054eb8030ebde76e$var$TOAST_NAME, __scopeToast);
    const [renderAnnounceText, setRenderAnnounceText] = h(false);
    const [isAnnounced, setIsAnnounced] = h(false);
    $054eb8030ebde76e$var$useNextFrame(
      () => setRenderAnnounceText(true)
    );
    p(() => {
      const timer = window.setTimeout(
        () => setIsAnnounced(true),
        1e3
      );
      return () => window.clearTimeout(timer);
    }, []);
    return isAnnounced ? null : /* @__PURE__ */ y$1($f1701beae083dbae$export$602eac185826482c, {
      asChild: true
    }, /* @__PURE__ */ y$1($ea1ef594cf570d83$export$439d29a4e110a164, announceProps, renderAnnounceText && /* @__PURE__ */ y$1(k$2, null, context.label, " ", children)));
  };
  const $054eb8030ebde76e$export$16d42d7c29b95a4 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeToast, ...titleProps } = props;
    return /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends({}, titleProps, {
      ref: forwardedRef
    }));
  });
  const $054eb8030ebde76e$export$ecddd96c53621d9a = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeToast, ...descriptionProps } = props;
    return /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends({}, descriptionProps, {
      ref: forwardedRef
    }));
  });
  const $054eb8030ebde76e$var$ACTION_NAME = "ToastAction";
  const $054eb8030ebde76e$export$3019feecfda683d2 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { altText, ...actionProps } = props;
    if (!altText)
      return null;
    return /* @__PURE__ */ y$1($054eb8030ebde76e$var$ToastAnnounceExclude, {
      altText,
      asChild: true
    }, /* @__PURE__ */ y$1($054eb8030ebde76e$export$811e70f61c205839, _extends({}, actionProps, {
      ref: forwardedRef
    })));
  });
  $054eb8030ebde76e$export$3019feecfda683d2.propTypes = {
    altText(props) {
      if (!props.altText)
        return new Error(`Missing prop \`altText\` expected on \`${$054eb8030ebde76e$var$ACTION_NAME}\``);
      return null;
    }
  };
  const $054eb8030ebde76e$var$CLOSE_NAME = "ToastClose";
  const $054eb8030ebde76e$export$811e70f61c205839 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeToast, ...closeProps } = props;
    const interactiveContext = $054eb8030ebde76e$var$useToastInteractiveContext($054eb8030ebde76e$var$CLOSE_NAME, __scopeToast);
    return /* @__PURE__ */ y$1($054eb8030ebde76e$var$ToastAnnounceExclude, {
      asChild: true
    }, /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.button, _extends({
      type: "button"
    }, closeProps, {
      ref: forwardedRef,
      onClick: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onClick, interactiveContext.onClose)
    })));
  });
  const $054eb8030ebde76e$var$ToastAnnounceExclude = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeToast, altText, ...announceExcludeProps } = props;
    return /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends({
      "data-radix-toast-announce-exclude": "",
      "data-radix-toast-announce-alt": altText || void 0
    }, announceExcludeProps, {
      ref: forwardedRef
    }));
  });
  function $054eb8030ebde76e$var$getAnnounceTextContent(container) {
    const textContent = [];
    const childNodes = Array.from(container.childNodes);
    childNodes.forEach((node) => {
      if (node.nodeType === node.TEXT_NODE && node.textContent)
        textContent.push(node.textContent);
      if ($054eb8030ebde76e$var$isHTMLElement(node)) {
        const isHidden = node.ariaHidden || node.hidden || node.style.display === "none";
        const isExcluded = node.dataset.radixToastAnnounceExclude === "";
        if (!isHidden) {
          if (isExcluded) {
            const altText = node.dataset.radixToastAnnounceAlt;
            if (altText)
              textContent.push(altText);
          } else
            textContent.push(...$054eb8030ebde76e$var$getAnnounceTextContent(node));
        }
      }
    });
    return textContent;
  }
  function $054eb8030ebde76e$var$handleAndDispatchCustomEvent(name2, handler, detail, { discrete }) {
    const currentTarget = detail.originalEvent.currentTarget;
    const event = new CustomEvent(name2, {
      bubbles: true,
      cancelable: true,
      detail
    });
    if (handler)
      currentTarget.addEventListener(name2, handler, {
        once: true
      });
    if (discrete)
      $8927f6f2acc4f386$export$6d1a0317bde7de7f(currentTarget, event);
    else
      currentTarget.dispatchEvent(event);
  }
  const $054eb8030ebde76e$var$isDeltaInDirection = (delta, direction, threshold = 0) => {
    const deltaX = Math.abs(delta.x);
    const deltaY = Math.abs(delta.y);
    const isDeltaX = deltaX > deltaY;
    if (direction === "left" || direction === "right")
      return isDeltaX && deltaX > threshold;
    else
      return !isDeltaX && deltaY > threshold;
  };
  function $054eb8030ebde76e$var$useNextFrame(callback = () => {
  }) {
    const fn2 = $b1b2314f5f9a1d84$export$25bec8c6f54ee79a(callback);
    $9f79659886946c16$export$e5c5a5f917a5871c(() => {
      let raf1 = 0;
      let raf2 = 0;
      raf1 = window.requestAnimationFrame(
        () => raf2 = window.requestAnimationFrame(fn2)
      );
      return () => {
        window.cancelAnimationFrame(raf1);
        window.cancelAnimationFrame(raf2);
      };
    }, [
      fn2
    ]);
  }
  function $054eb8030ebde76e$var$isHTMLElement(node) {
    return node.nodeType === node.ELEMENT_NODE;
  }
  function $054eb8030ebde76e$var$getTabbableCandidates(container) {
    const nodes = [];
    const walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
      acceptNode: (node) => {
        const isHiddenInput = node.tagName === "INPUT" && node.type === "hidden";
        if (node.disabled || node.hidden || isHiddenInput)
          return NodeFilter.FILTER_SKIP;
        return node.tabIndex >= 0 ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_SKIP;
      }
    });
    while (walker.nextNode())
      nodes.push(walker.currentNode);
    return nodes;
  }
  function $054eb8030ebde76e$var$focusFirst(candidates) {
    const previouslyFocusedElement = document.activeElement;
    return candidates.some((candidate) => {
      if (candidate === previouslyFocusedElement)
        return true;
      candidate.focus();
      return document.activeElement !== previouslyFocusedElement;
    });
  }
  const $054eb8030ebde76e$export$2881499e37b75b9a = $054eb8030ebde76e$export$f5d03d415824e0e;
  const $054eb8030ebde76e$export$d5c6c08dc2d3ca7 = $054eb8030ebde76e$export$6192c2425ecfd989;
  const $054eb8030ebde76e$export$be92b6f5f03c0fe9 = $054eb8030ebde76e$export$8d8dc7d5f743331b;
  const $054eb8030ebde76e$export$f99233281efd08a0 = $054eb8030ebde76e$export$16d42d7c29b95a4;
  const $054eb8030ebde76e$export$393edc798c47379d = $054eb8030ebde76e$export$ecddd96c53621d9a;
  const $054eb8030ebde76e$export$e19cd5f9376f8cee = $054eb8030ebde76e$export$3019feecfda683d2;
  const NotificationToast = (props) => {
    const [open, setOpen] = h(false);
    const timerRef = _$2(0);
    p(() => {
      if (props.options.title.length > 0 && props.options.text.length > 0) {
        setOpen(true);
        return () => clearTimeout(timerRef.current);
      }
    }, [props.options]);
    return o($054eb8030ebde76e$export$2881499e37b75b9a, {
      swipeDirection: "right",
      children: [o($054eb8030ebde76e$export$be92b6f5f03c0fe9, {
        className: `ToastRoot
        ${props.options.type === NotificationType.WARNING ? " NotificationWarn" : ""}
            ${props.options.type === NotificationType.ERROR ? " NotificationErr" : ""}`,
        open,
        onOpenChange: setOpen,
        duration: props.options.timeout,
        children: [o($054eb8030ebde76e$export$f99233281efd08a0, {
          className: `ToastTitle
          ${props.options.type === NotificationType.WARNING ? " NotificationWarn" : ""}
            ${props.options.type === NotificationType.ERROR ? " NotificationErr" : ""}`,
          children: [instance.t(`${LANG_NS_MAIN}:shortTitle`), ": ", props.options.title]
        }), o($054eb8030ebde76e$export$393edc798c47379d, {
          asChild: true,
          children: o("div", {
            className: `ToastDescription
            ${props.options.type === NotificationType.WARNING ? " NotificationWarn" : ""}
            ${props.options.type === NotificationType.ERROR ? " NotificationErr" : ""}`,
            children: props.options.text
          })
        }), props.options.showClose && o($054eb8030ebde76e$export$e19cd5f9376f8cee, {
          className: "ToastAction",
          asChild: true,
          altText: "Close",
          children: o("button", {
            className: `Button
            ${props.options.type === NotificationType.NOTIFICATION ? " green" : ""}
            ${props.options.type === NotificationType.WARNING || props.options.type === NotificationType.ERROR ? " violet" : ""}`,
            children: "OK"
          })
        })]
      }), o($054eb8030ebde76e$export$d5c6c08dc2d3ca7, {
        className: "ToastViewport"
      })]
    });
  };
  const $6be4966fd9bbc698$var$SWITCH_NAME = "Switch";
  const [$6be4966fd9bbc698$var$createSwitchContext, $6be4966fd9bbc698$export$cf7f5f17f69cbd43] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($6be4966fd9bbc698$var$SWITCH_NAME);
  const [$6be4966fd9bbc698$var$SwitchProvider, $6be4966fd9bbc698$var$useSwitchContext] = $6be4966fd9bbc698$var$createSwitchContext($6be4966fd9bbc698$var$SWITCH_NAME);
  const $6be4966fd9bbc698$export$b5d5cf8927ab7262 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeSwitch, name: name2, checked: checkedProp, defaultChecked, required, disabled, value = "on", onCheckedChange, ...switchProps } = props;
    const [button, setButton] = h(null);
    const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(
      forwardedRef,
      (node) => setButton(node)
    );
    const hasConsumerStoppedPropagationRef = _$2(false);
    const isFormControl = button ? Boolean(button.closest("form")) : true;
    const [checked = false, setChecked] = $71cd76cc60e0454e$export$6f32135080cb4c3({
      prop: checkedProp,
      defaultProp: defaultChecked,
      onChange: onCheckedChange
    });
    return /* @__PURE__ */ y$1($6be4966fd9bbc698$var$SwitchProvider, {
      scope: __scopeSwitch,
      checked,
      disabled
    }, /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.button, _extends({
      type: "button",
      role: "switch",
      "aria-checked": checked,
      "aria-required": required,
      "data-state": $6be4966fd9bbc698$var$getState(checked),
      "data-disabled": disabled ? "" : void 0,
      disabled,
      value
    }, switchProps, {
      ref: composedRefs,
      onClick: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onClick, (event) => {
        setChecked(
          (prevChecked) => !prevChecked
        );
        if (isFormControl) {
          hasConsumerStoppedPropagationRef.current = event.isPropagationStopped();
          if (!hasConsumerStoppedPropagationRef.current)
            event.stopPropagation();
        }
      })
    })), isFormControl && /* @__PURE__ */ y$1($6be4966fd9bbc698$var$BubbleInput, {
      control: button,
      bubbles: !hasConsumerStoppedPropagationRef.current,
      name: name2,
      value,
      checked,
      required,
      disabled,
      style: {
        transform: "translateX(-100%)"
      }
    }));
  });
  const $6be4966fd9bbc698$var$THUMB_NAME = "SwitchThumb";
  const $6be4966fd9bbc698$export$4d07bf653ea69106 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeSwitch, ...thumbProps } = props;
    const context = $6be4966fd9bbc698$var$useSwitchContext($6be4966fd9bbc698$var$THUMB_NAME, __scopeSwitch);
    return /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.span, _extends({
      "data-state": $6be4966fd9bbc698$var$getState(context.checked),
      "data-disabled": context.disabled ? "" : void 0
    }, thumbProps, {
      ref: forwardedRef
    }));
  });
  const $6be4966fd9bbc698$var$BubbleInput = (props) => {
    const { control, checked, bubbles = true, ...inputProps } = props;
    const ref2 = _$2(null);
    const prevChecked = $010c2913dbd2fe3d$export$5cae361ad82dce8b(checked);
    const controlSize = $db6c3485150b8e66$export$1ab7ae714698c4b8(control);
    p(() => {
      const input = ref2.current;
      const inputProto = window.HTMLInputElement.prototype;
      const descriptor = Object.getOwnPropertyDescriptor(inputProto, "checked");
      const setChecked = descriptor.set;
      if (prevChecked !== checked && setChecked) {
        const event = new Event("click", {
          bubbles
        });
        setChecked.call(input, checked);
        input.dispatchEvent(event);
      }
    }, [
      prevChecked,
      checked,
      bubbles
    ]);
    return /* @__PURE__ */ y$1("input", _extends({
      type: "checkbox",
      "aria-hidden": true,
      defaultChecked: checked
    }, inputProps, {
      tabIndex: -1,
      ref: ref2,
      style: {
        ...props.style,
        ...controlSize,
        position: "absolute",
        pointerEvents: "none",
        opacity: 0,
        margin: 0
      }
    }));
  };
  function $6be4966fd9bbc698$var$getState(checked) {
    return checked ? "checked" : "unchecked";
  }
  const $6be4966fd9bbc698$export$be92b6f5f03c0fe9 = $6be4966fd9bbc698$export$b5d5cf8927ab7262;
  const $6be4966fd9bbc698$export$6521433ed15a34db = $6be4966fd9bbc698$export$4d07bf653ea69106;
  const $ce77a8961b41be9e$var$RADIO_NAME = "Radio";
  const [$ce77a8961b41be9e$var$createRadioContext, $ce77a8961b41be9e$export$67d2296460f1b002] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($ce77a8961b41be9e$var$RADIO_NAME);
  const [$ce77a8961b41be9e$var$RadioProvider, $ce77a8961b41be9e$var$useRadioContext] = $ce77a8961b41be9e$var$createRadioContext($ce77a8961b41be9e$var$RADIO_NAME);
  const $ce77a8961b41be9e$export$d7b12c4107be0d61 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeRadio, name: name2, checked = false, required, disabled, value = "on", onCheck, ...radioProps } = props;
    const [button, setButton] = h(null);
    const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(
      forwardedRef,
      (node) => setButton(node)
    );
    const hasConsumerStoppedPropagationRef = _$2(false);
    const isFormControl = button ? Boolean(button.closest("form")) : true;
    return /* @__PURE__ */ y$1($ce77a8961b41be9e$var$RadioProvider, {
      scope: __scopeRadio,
      checked,
      disabled
    }, /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.button, _extends({
      type: "button",
      role: "radio",
      "aria-checked": checked,
      "data-state": $ce77a8961b41be9e$var$getState(checked),
      "data-disabled": disabled ? "" : void 0,
      disabled,
      value
    }, radioProps, {
      ref: composedRefs,
      onClick: $e42e1063c40fb3ef$export$b9ecd428b558ff10(props.onClick, (event) => {
        if (!checked)
          onCheck === null || onCheck === void 0 || onCheck();
        if (isFormControl) {
          hasConsumerStoppedPropagationRef.current = event.isPropagationStopped();
          if (!hasConsumerStoppedPropagationRef.current)
            event.stopPropagation();
        }
      })
    })), isFormControl && /* @__PURE__ */ y$1($ce77a8961b41be9e$var$BubbleInput, {
      control: button,
      bubbles: !hasConsumerStoppedPropagationRef.current,
      name: name2,
      value,
      checked,
      required,
      disabled,
      style: {
        transform: "translateX(-100%)"
      }
    }));
  });
  const $ce77a8961b41be9e$var$INDICATOR_NAME = "RadioIndicator";
  const $ce77a8961b41be9e$export$d35a9ffa9a04f9e7 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeRadio, forceMount, ...indicatorProps } = props;
    const context = $ce77a8961b41be9e$var$useRadioContext($ce77a8961b41be9e$var$INDICATOR_NAME, __scopeRadio);
    return /* @__PURE__ */ y$1($921a889cee6df7e8$export$99c2b779aa4e8b8b, {
      present: forceMount || context.checked
    }, /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.span, _extends({
      "data-state": $ce77a8961b41be9e$var$getState(context.checked),
      "data-disabled": context.disabled ? "" : void 0
    }, indicatorProps, {
      ref: forwardedRef
    })));
  });
  const $ce77a8961b41be9e$var$BubbleInput = (props) => {
    const { control, checked, bubbles = true, ...inputProps } = props;
    const ref2 = _$2(null);
    const prevChecked = $010c2913dbd2fe3d$export$5cae361ad82dce8b(checked);
    const controlSize = $db6c3485150b8e66$export$1ab7ae714698c4b8(control);
    p(() => {
      const input = ref2.current;
      const inputProto = window.HTMLInputElement.prototype;
      const descriptor = Object.getOwnPropertyDescriptor(inputProto, "checked");
      const setChecked = descriptor.set;
      if (prevChecked !== checked && setChecked) {
        const event = new Event("click", {
          bubbles
        });
        setChecked.call(input, checked);
        input.dispatchEvent(event);
      }
    }, [
      prevChecked,
      checked,
      bubbles
    ]);
    return /* @__PURE__ */ y$1("input", _extends({
      type: "radio",
      "aria-hidden": true,
      defaultChecked: checked
    }, inputProps, {
      tabIndex: -1,
      ref: ref2,
      style: {
        ...props.style,
        ...controlSize,
        position: "absolute",
        pointerEvents: "none",
        opacity: 0,
        margin: 0
      }
    }));
  };
  function $ce77a8961b41be9e$var$getState(checked) {
    return checked ? "checked" : "unchecked";
  }
  const $f99a8c78507165f7$var$ARROW_KEYS = [
    "ArrowUp",
    "ArrowDown",
    "ArrowLeft",
    "ArrowRight"
  ];
  const $f99a8c78507165f7$var$RADIO_GROUP_NAME = "RadioGroup";
  const [$f99a8c78507165f7$var$createRadioGroupContext, $f99a8c78507165f7$export$c547093f11b76da2] = $c512c27ab02ef895$export$50c7b4e9d9f19c1($f99a8c78507165f7$var$RADIO_GROUP_NAME, [
    $d7bdfb9eb0fdf311$export$c7109489551a4f4,
    $ce77a8961b41be9e$export$67d2296460f1b002
  ]);
  const $f99a8c78507165f7$var$useRovingFocusGroupScope = $d7bdfb9eb0fdf311$export$c7109489551a4f4();
  const $f99a8c78507165f7$var$useRadioScope = $ce77a8961b41be9e$export$67d2296460f1b002();
  const [$f99a8c78507165f7$var$RadioGroupProvider, $f99a8c78507165f7$var$useRadioGroupContext] = $f99a8c78507165f7$var$createRadioGroupContext($f99a8c78507165f7$var$RADIO_GROUP_NAME);
  const $f99a8c78507165f7$export$a98f0dcb43a68a25 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeRadioGroup, name: name2, defaultValue: defaultValue2, value: valueProp, required = false, disabled = false, orientation, dir, loop = true, onValueChange, ...groupProps } = props;
    const rovingFocusGroupScope = $f99a8c78507165f7$var$useRovingFocusGroupScope(__scopeRadioGroup);
    const direction = $f631663db3294ace$export$b39126d51d94e6f3(dir);
    const [value, setValue] = $71cd76cc60e0454e$export$6f32135080cb4c3({
      prop: valueProp,
      defaultProp: defaultValue2,
      onChange: onValueChange
    });
    return /* @__PURE__ */ y$1($f99a8c78507165f7$var$RadioGroupProvider, {
      scope: __scopeRadioGroup,
      name: name2,
      required,
      disabled,
      value,
      onValueChange: setValue
    }, /* @__PURE__ */ y$1($d7bdfb9eb0fdf311$export$be92b6f5f03c0fe9, _extends({
      asChild: true
    }, rovingFocusGroupScope, {
      orientation,
      dir: direction,
      loop
    }), /* @__PURE__ */ y$1($8927f6f2acc4f386$export$250ffa63cdc0d034.div, _extends({
      role: "radiogroup",
      "aria-required": required,
      "aria-orientation": orientation,
      "data-disabled": disabled ? "" : void 0,
      dir: direction
    }, groupProps, {
      ref: forwardedRef
    }))));
  });
  const $f99a8c78507165f7$var$ITEM_NAME = "RadioGroupItem";
  const $f99a8c78507165f7$export$9f866c100ef519e4 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeRadioGroup, disabled, ...itemProps } = props;
    const context = $f99a8c78507165f7$var$useRadioGroupContext($f99a8c78507165f7$var$ITEM_NAME, __scopeRadioGroup);
    const isDisabled = context.disabled || disabled;
    const rovingFocusGroupScope = $f99a8c78507165f7$var$useRovingFocusGroupScope(__scopeRadioGroup);
    const radioScope = $f99a8c78507165f7$var$useRadioScope(__scopeRadioGroup);
    const ref2 = _$2(null);
    const composedRefs = $6ed0406888f73fc4$export$c7b2cbe3552a0d05(forwardedRef, ref2);
    const checked = context.value === itemProps.value;
    const isArrowKeyPressedRef = _$2(false);
    p(() => {
      const handleKeyDown = (event) => {
        if ($f99a8c78507165f7$var$ARROW_KEYS.includes(event.key))
          isArrowKeyPressedRef.current = true;
      };
      const handleKeyUp = () => isArrowKeyPressedRef.current = false;
      document.addEventListener("keydown", handleKeyDown);
      document.addEventListener("keyup", handleKeyUp);
      return () => {
        document.removeEventListener("keydown", handleKeyDown);
        document.removeEventListener("keyup", handleKeyUp);
      };
    }, []);
    return /* @__PURE__ */ y$1($d7bdfb9eb0fdf311$export$6d08773d2e66f8f2, _extends({
      asChild: true
    }, rovingFocusGroupScope, {
      focusable: !isDisabled,
      active: checked
    }), /* @__PURE__ */ y$1($ce77a8961b41be9e$export$d7b12c4107be0d61, _extends({
      disabled: isDisabled,
      required: context.required,
      checked
    }, radioScope, itemProps, {
      name: context.name,
      ref: composedRefs,
      onCheck: () => context.onValueChange(itemProps.value),
      onKeyDown: $e42e1063c40fb3ef$export$b9ecd428b558ff10((event) => {
        if (event.key === "Enter")
          event.preventDefault();
      }),
      onFocus: $e42e1063c40fb3ef$export$b9ecd428b558ff10(itemProps.onFocus, () => {
        var _ref$current;
        if (isArrowKeyPressedRef.current)
          (_ref$current = ref2.current) === null || _ref$current === void 0 || _ref$current.click();
      })
    })));
  });
  const $f99a8c78507165f7$export$5fb54c671a65c88 = /* @__PURE__ */ k((props, forwardedRef) => {
    const { __scopeRadioGroup, ...indicatorProps } = props;
    const radioScope = $f99a8c78507165f7$var$useRadioScope(__scopeRadioGroup);
    return /* @__PURE__ */ y$1($ce77a8961b41be9e$export$d35a9ffa9a04f9e7, _extends({}, radioScope, indicatorProps, {
      ref: forwardedRef
    }));
  });
  const $f99a8c78507165f7$export$be92b6f5f03c0fe9 = $f99a8c78507165f7$export$a98f0dcb43a68a25;
  const $f99a8c78507165f7$export$6d08773d2e66f8f2 = $f99a8c78507165f7$export$9f866c100ef519e4;
  const $f99a8c78507165f7$export$adb584737d712b70 = $f99a8c78507165f7$export$5fb54c671a65c88;
  const SettingsDialogue = () => {
    const firebaseContext = q$1(FirebaseContext);
    const notificationContext = q$1(NotificationContext);
    const settingsContext = q$1(SettingsContext);
    const [initialLanguage, setInitialLanguage] = h(void 0);
    p(() => {
      if (initialLanguage === void 0) {
        setInitialLanguage(settingsContext.options.language);
      } else if (initialLanguage !== settingsContext.options.language) {
        location.reload();
      }
    }, [settingsContext.options.language]);
    const firebaseConfigurationParsing = async (rawStringConfig) => {
      let parsedFirebaseConfig = void 0;
      try {
        const startIndex = rawStringConfig.indexOf("{");
        const endIndex = rawStringConfig.lastIndexOf("}");
        const configString = rawStringConfig.slice(startIndex, endIndex + 1);
        const compactConfigString = configString.replace(/\s/g, "");
        const quotedConfigString = compactConfigString.replace(/([{,])\s*(\w+)\s*:/g, '$1"$2":');
        parsedFirebaseConfig = JSON.parse(quotedConfigString);
        return parsedFirebaseConfig;
      } catch (e2) {
        notificationContext.setOptions({
          type: NotificationType.ERROR,
          title: instance.t(`${LANG_NS_MAIN}:settingFirebaseConfigurationErrorTitle`),
          text: instance.t(`${LANG_NS_MAIN}:settingFirebaseConfigurationErrorParseText`)
        });
        throw new Error("firebaseConfigurationParsing(): Parser error");
      }
    };
    const firebaseConfigurationTest = async (firebaseConfig) => {
      const app = initializeApp(firebaseConfig);
      const db = getDatabase(app);
      try {
        await set(ref(db, "testingConfig/"), {
          testKey: "testValue"
        });
      } catch (error2) {
        const firebaseError = error2;
        if (firebaseError.code === "PERMISSION_DENIED") {
          if (app) {
            await deleteApp(app);
          }
          notificationContext.setOptions({
            type: NotificationType.ERROR,
            title: instance.t(`${LANG_NS_MAIN}:settingFirebaseConfigurationErrorTitle`),
            text: instance.t(`${LANG_NS_MAIN}:settingFirebaseConfigurationErrorUsageWriteText`)
          });
          throw new Error("firebaseConfigurationTest(): Write error");
        }
      }
      try {
        await get(ref(db, "testingConfig/"));
      } catch (error2) {
        const firebaseError = error2;
        if (firebaseError.message === "Permission denied") {
          if (app) {
            await deleteApp(app);
          }
          notificationContext.setOptions({
            type: NotificationType.ERROR,
            title: instance.t(`${LANG_NS_MAIN}:settingFirebaseConfigurationErrorTitle`),
            text: instance.t(`${LANG_NS_MAIN}:settingFirebaseConfigurationErrorUsageReadText`)
          });
          throw new Error("firebaseConfigurationTest(): Read error");
        }
      }
      try {
        await set(ref(db, "testingConfig/"), {});
      } catch {
        if (app) {
          await deleteApp(app);
        }
        notificationContext.setOptions({
          type: NotificationType.ERROR,
          title: instance.t(`${LANG_NS_MAIN}:settingFirebaseConfigurationErrorTitle`),
          text: instance.t(`${LANG_NS_MAIN}:settingFirebaseConfigurationErrorUsageWriteText`)
        });
        throw new Error("firebaseConfigurationTest(): Write error");
      }
      return {
        app,
        db
      };
    };
    const onClickCloseDialogueAndSaveSettings = async () => {
      var _a2, _b, _c, _d, _e, _f, _g, _h;
      const selectedLanguageState = (_a2 = document.querySelector(SETTING_LANGUAGE_RADIO_BUTTON_CHECKED_SELECTOR)) == null ? void 0 : _a2.value;
      const enableCustomSelectionState = (_c = (_b = document.getElementById(SETTING_ENABLE_CUSTOM_SELECTIONS_ID)) == null ? void 0 : _b.dataset) == null ? void 0 : _c.state;
      const enableLoadAllPagesState = (_e = (_d = document.getElementById(SETTING_ENABLE_LOAD_ALL_PAGES_ID)) == null ? void 0 : _d.dataset) == null ? void 0 : _e.state;
      const enableFirebaseSyncState = (_g = (_f = document.getElementById(SETTING_ENABLE_FIREBASE_SYNC_ID)) == null ? void 0 : _f.dataset) == null ? void 0 : _g.state;
      const enteredFirebaseConfigState = (_h = document.getElementById(SETTING_FIREBASE_SYNC_CONF_ID)) == null ? void 0 : _h.value;
      const selectedLanguage = selectedLanguageState ? selectedLanguageState : settingsContext.options.language;
      const enableCustomSelections = enableCustomSelectionState ? enableCustomSelectionState === "checked" : settingsContext.options.enableCustomSelection;
      const enableLoadAllPages = enableLoadAllPagesState ? enableLoadAllPagesState === "checked" : settingsContext.options.enableLoadAllPages;
      const enableFirebaseSync = enableFirebaseSyncState ? enableFirebaseSyncState === "checked" : settingsContext.options.enableFirebaseSync;
      const firebaseConfig = enteredFirebaseConfigState ? enteredFirebaseConfigState : void 0;
      if (enableFirebaseSync && (firebaseConfig && firebaseConfig.length === 0 || !firebaseConfig)) {
        notificationContext.setOptions({
          type: NotificationType.ERROR,
          title: instance.t(`${LANG_NS_MAIN}:settingFirebaseConfigurationErrorTitle`),
          text: instance.t(`${LANG_NS_MAIN}:settingFirebaseConfigurationErrorParseText`)
        });
        return;
      } else if (enableFirebaseSync && firebaseConfig) {
        try {
          const parsedFirebaseConfig = await firebaseConfigurationParsing(enteredFirebaseConfigState);
          if (parsedFirebaseConfig && JSON.stringify(firebaseContext.config) !== JSON.stringify(parsedFirebaseConfig)) {
            try {
              await firebaseConfigurationTest(parsedFirebaseConfig);
              firebaseContext.setConfig(parsedFirebaseConfig);
              ScriptStorage.set(PERSIST_KEY_FIREBASE_CONFIG, parsedFirebaseConfig);
            } catch {
              return;
            }
          }
        } catch {
          return;
        }
      }
      const newSettings = {
        ...settingsContext.options,
        language: selectedLanguage,
        enableCustomSelection: enableCustomSelections,
        enableLoadAllPages,
        enableFirebaseSync,
        firebaseConfig
      };
      notificationContext.setOptions({
        type: NotificationType.NOTIFICATION,
        title: instance.t(`${LANG_NS_MAIN}:settings`),
        text: instance.t(`${LANG_NS_MAIN}:settingsSaved`),
        timeout: 2e3
      });
      settingsContext.setOptions({
        ...newSettings
      });
      settingsContext.setClosed();
    };
    return o($5d3850c4d0b4e6c7$export$be92b6f5f03c0fe9, {
      open: settingsContext.open,
      children: o($5d3850c4d0b4e6c7$export$602eac185826482c, {
        children: [o($5d3850c4d0b4e6c7$export$c6fdb837b070b4ff, {
          className: "DialogOverlay"
        }), o($5d3850c4d0b4e6c7$export$7c6e2c02157bb7d2, {
          className: "DialogContent",
          children: [o($5d3850c4d0b4e6c7$export$f99233281efd08a0, {
            className: "DialogTitle",
            children: instance.t(`${LANG_NS_MAIN}:menuWLESettings`)
          }), o("div", {
            className: "DialogContentScroll",
            children: [o($5d3850c4d0b4e6c7$export$393edc798c47379d, {
              className: "DialogDescription",
              children: instance.t(`${LANG_NS_MAIN}:settingGeneralDescription`)
            }), o("fieldset", {
              className: "Fieldset",
              children: [o("label", {
                className: "Label",
                children: instance.t(`${LANG_NS_MAIN}:settingWLELanguage`)
              }), o($f99a8c78507165f7$export$be92b6f5f03c0fe9, {
                className: "RadioGroupRoot",
                defaultValue: settingsContext.options.language,
                "aria-label": "Choose a language",
                children: AvailableLocales.map((curLocale) => {
                  var _a2;
                  return o("div", {
                    style: {
                      display: "flex",
                      alignItems: "center"
                    },
                    children: [o($f99a8c78507165f7$export$6d08773d2e66f8f2, {
                      className: "RadioGroupItem",
                      value: curLocale,
                      id: `${SETTING_LANGUAGE_RADIO_BUTTON_BASE_ID}-${curLocale}`,
                      children: o($f99a8c78507165f7$export$adb584737d712b70, {
                        className: "RadioGroupIndicator"
                      })
                    }), o("label", {
                      className: "Label",
                      htmlFor: `${SETTING_LANGUAGE_RADIO_BUTTON_BASE_ID}-${curLocale}`,
                      children: instance.t(`${LANG_NS_MAIN}:${(_a2 = getLanguageConfByCode(curLocale)) == null ? void 0 : _a2.i18nNameKey}`)
                    })]
                  });
                })
              })]
            }), o("fieldset", {
              className: "Fieldset Switch",
              children: [o("label", {
                className: "Label",
                htmlFor: SETTING_ENABLE_CUSTOM_SELECTIONS_ID,
                children: instance.t(`${LANG_NS_MAIN}:settingActivateSelection`)
              }), o($6be4966fd9bbc698$export$be92b6f5f03c0fe9, {
                className: "SwitchRoot",
                id: SETTING_ENABLE_CUSTOM_SELECTIONS_ID,
                defaultChecked: settingsContext.options.enableCustomSelection,
                children: o($6be4966fd9bbc698$export$6521433ed15a34db, {
                  className: "SwitchThumb"
                })
              })]
            }), o("fieldset", {
              className: "Fieldset Switch",
              children: [o("label", {
                className: "Label",
                htmlFor: SETTING_ENABLE_LOAD_ALL_PAGES_ID,
                children: instance.t(`${LANG_NS_MAIN}:settingActivateLoadAllPages`)
              }), o($6be4966fd9bbc698$export$be92b6f5f03c0fe9, {
                className: "SwitchRoot",
                id: SETTING_ENABLE_LOAD_ALL_PAGES_ID,
                defaultChecked: settingsContext.options.enableLoadAllPages,
                children: o($6be4966fd9bbc698$export$6521433ed15a34db, {
                  className: "SwitchThumb"
                })
              })]
            }), o("fieldset", {
              className: "Fieldset Switch",
              children: [o("label", {
                className: "Label",
                htmlFor: SETTING_ENABLE_FIREBASE_SYNC_ID,
                children: instance.t(`${LANG_NS_MAIN}:settingActivateFirebaseSync`)
              }), o($6be4966fd9bbc698$export$be92b6f5f03c0fe9, {
                className: "SwitchRoot",
                id: SETTING_ENABLE_FIREBASE_SYNC_ID,
                defaultChecked: settingsContext.options.enableFirebaseSync,
                children: o($6be4966fd9bbc698$export$6521433ed15a34db, {
                  className: "SwitchThumb"
                })
              })]
            }), o("fieldset", {
              className: "Fieldset",
              children: [o("label", {
                className: "Label",
                htmlFor: SETTING_FIREBASE_SYNC_CONF_ID,
                children: instance.t(`${LANG_NS_MAIN}:settingFirebaseConfiguration`)
              }), o("textarea", {
                className: "Textarea TextareaSmall TextareaCode",
                id: SETTING_FIREBASE_SYNC_CONF_ID,
                value: settingsContext.options.firebaseConfig ? settingsContext.options.firebaseConfig : ""
              })]
            })]
          }), o("div", {
            className: "ButtonGroup",
            children: o("button", {
              className: "Button green",
              onClick: onClickCloseDialogueAndSaveSettings,
              children: instance.t(`${LANG_NS_MAIN}:save`)
            })
          }), o("button", {
            className: "IconButton",
            "aria-label": "Close",
            onClick: settingsContext.setClosed,
            children: o(Cross2Icon, {})
          })]
        })]
      })
    });
  };
  function MainUserscriptComponent() {
    const notificationContext = q$1(NotificationContext);
    const settingsContext = q$1(SettingsContext);
    const sectionSelectionContext = q$1(SectionSelectionContext);
    const [addedScrollEventOnce, setAddedScrollEventOnce] = h(false);
    const [updatedStatisticsOnce, setUpdatedStatisticsOnce] = h(false);
    p(() => {
      const lastPage = ScriptStorage.get(PERSIST_KEY_LAST_PAGE);
      const currentPage = window.location.pathname;
      ScriptStorage.set(PERSIST_KEY_LAST_PAGE, currentPage);
      if (!addedScrollEventOnce) {
        const curScrollBounds = {
          maxY: window.scrollY,
          minY: window.scrollY
        };
        setAddedScrollEventOnce(true);
        addEventListener("scroll", () => {
          const topBarContainer = document.querySelector(".TopBarContainer");
          if (!topBarContainer) {
            return;
          }
          if (window.scrollY < curScrollBounds.minY || topBarContainer.classList.contains("ScrollMinimize")) {
            curScrollBounds.minY = window.scrollY;
          }
          if (window.scrollY > curScrollBounds.maxY || !topBarContainer.classList.contains("ScrollMinimize")) {
            curScrollBounds.maxY = window.scrollY;
          }
          if (window.scrollY > curScrollBounds.minY + 50) {
            topBarContainer.classList.add("ScrollMinimize");
          } else if (window.scrollY < curScrollBounds.maxY - 50) {
            topBarContainer.classList.remove("ScrollMinimize");
          }
        });
      }
      if (settingsContext.options.enableCustomSelection && !updatedStatisticsOnce) {
        setUpdatedStatisticsOnce(true);
        if (verifyOnPagePractice(lastPage ? lastPage : "") && verifyOnPagePracticeEnd(currentPage)) {
          const regexpCurExerciseAndSections = /\/practice\/([0-9]+)\/([0-9,]+)\/practice\/end/;
          const matchExercise = window.location.pathname.match(regexpCurExerciseAndSections);
          if (matchExercise) {
            const [, matchExerciseID, matchSectionsIDs] = matchExercise;
            const sectionIDs = matchSectionsIDs.split(",");
            const sectionIDHashCode = getCustomSelectionHash({
              exerciseID: matchExerciseID,
              sectionsKeys: sectionIDs
            });
            const existingCustomSelection = getCustomSelectionFromHash({
              hash: sectionIDHashCode,
              sectionSelectionContext
            });
            if (existingCustomSelection) {
              const practicesToday2 = existingCustomSelection.lastPracticed && isDateToday(new Date(existingCustomSelection.lastPracticed)) && existingCustomSelection.practicesToday ? existingCustomSelection.practicesToday + 1 : 1;
              sectionSelectionContext.updateLastPracticedInCustomSelectionsStorage({
                hash: sectionIDHashCode
              });
              notificationContext.setOptions({
                title: instance.t(`${LANG_NS_MAIN}:actionPracticeEndNotificationTitle`),
                text: instance.t(`${LANG_NS_MAIN}:actionPracticeEndNotificationText`, {
                  count: practicesToday2,
                  exercise: existingCustomSelection.name
                }),
                type: NotificationType.NOTIFICATION
              });
            }
          }
        }
      }
    });
    return o(k$2, {
      children: [o(FirebaseSyncDialogue, {}), o(CustomSelectionsStorageDialogue, {}), o(CustomSelectionSaveDialogue, {}), o(SettingsDialogue, {}), o(AlertDialogue, {}), o(NotificationToast, {
        options: notificationContext.options
      })]
    });
  }
  const WordalistMenuPortal = (props) => {
    return o("li", {
      id: props.id,
      children: o("a", {
        href: "#",
        onClick: (event) => {
          event.stopPropagation();
          event.preventDefault();
          props.onClickCallback(event);
        },
        children: props.children
      })
    });
  };
  let wlPersonalMenuElement = null;
  let wlBottomMenuElement = null;
  if (!verifyOnPagePractice()) {
    try {
      wlPersonalMenuElement = synchronousWaitForElement(ELEM_WL_PERSONAL_MENU_SELECTOR);
      wlBottomMenuElement = synchronousWaitForElement(ELEM_WL_BOTTOM_MENU_SELECTOR);
    } catch (e2) {
      console.warn(`Could not find element. Message: `, e2.message);
    }
  }
  let wlTopBarElement = null;
  if (verifyOnLoggedInPage() && !verifyOnPagePractice()) {
    try {
      wlTopBarElement = synchronousWaitForElement(ELEM_WL_LOGGED_IN_TOP_BAR_SELECTOR);
    } catch (e2) {
      console.warn(`Could not find element. Message: `, e2.message);
    }
  }
  removeDuplicatedComponent(ELEM_MAIN_APP_ID);
  removeDuplicatedComponent(ELEM_PERSONAL_MENU_ITEM_WLE_SELECTION_ID);
  removeDuplicatedComponent(ELEM_PERSONAL_MENU_ITEM_WLE_SYNCHRONIZATION_ID);
  removeDuplicatedComponent(ELEM_BOTTOM_MENU_ITEM_WLE_SETTINGS_ID);
  removeDuplicatedComponent(ELEM_LOGGED_IN_TOP_BAR_CONTAINER_ID);
  removeDuplicatedComponent(ELEM_PAGE_EXERCISE_SECTIONS_TOOLBAR_CONTAINER_ID);
  if (verifyOnLoggedInPage() && !verifyOnPagePractice() && wlTopBarElement) {
    const topBarElement = document.createElement("div");
    topBarElement.id = ELEM_LOGGED_IN_TOP_BAR_CONTAINER_ID;
    wlTopBarElement.append(topBarElement);
  }
  let wlPageExerciseToolbarContainerElement;
  let wlPageExerciseSectionsAddedIDs = [];
  const wlPageExerciseSectionsAddedPortals = [];
  if (verifyOnPageExercise()) {
    prepareExercisePageToolbar();
    wlPageExerciseToolbarContainerElement = synchronousWaitForElement(`#${ELEM_PAGE_EXERCISE_SECTIONS_TOOLBAR_CONTAINER_ID}`);
    wlPageExerciseSectionsAddedIDs = prepareExercisePageSections();
    wlPageExerciseSectionsAddedIDs.forEach(({
      elementID,
      exerciseID,
      sectionID,
      exerciseTitle,
      sectionTitle
    }) => {
      const addedElement = synchronousWaitForElement(`#${elementID}`);
      wlPageExerciseSectionsAddedPortals.push(z(o(WordalistExerciseSectionCheckbox, {
        id: `${elementID}-checkbox`,
        exerciseID,
        sectionID,
        exerciseTitle,
        sectionTitle
      }), addedElement));
    });
  }
  let wlPageExerciseExploreSectionToolbarContainerElement;
  if (verifyOnPageExerciseExploreSection()) {
    prepareExerciseExploreSectionPageToolbar();
    wlPageExerciseExploreSectionToolbarContainerElement = synchronousWaitForElement(`#${ELEM_PAGE_EXERCISE_EXPLORE_SECTIONS_TOOLBAR_CONTAINER_ID}`);
  }
  const UserscriptApp = () => {
    const savedSettingLanguage = ScriptStorage.get(PERSIST_KEY_LANGUAGE_SETTING);
    const savedSettingEnableCustomSelections = ScriptStorage.get(PERSIST_KEY_ENABLE_CUSTOM_SELECTIONS_SETTING);
    const savedSettingEnableLoadAllPages = ScriptStorage.get(PERSIST_KEY_ENABLE_LOAD_ALL_PAGES_SETTING);
    const savedSettingEnableFirebaseSync = ScriptStorage.get(PERSIST_KEY_ENABLE_FIREBASE_SYNC_SETTING);
    const savedSettingFirebaseConf = ScriptStorage.get(PERSIST_KEY_FIREBASE_SYNC_CONF_SETTING);
    const savedCustomSelectionsActiveExercise = ScriptStorage.get(PERSIST_KEY_CUSTOM_SELECTIONS_ACTIVE_EXERCISE);
    const savedCustomSelectionsActiveSections = ScriptStorage.get(PERSIST_KEY_CUSTOM_SELECTIONS_ACTIVE_SECTIONS);
    const savedCustomSelectionsExercisesStorage = ScriptStorage.get(PERSIST_KEY_CUSTOM_SELECTIONS_EXERCISES_STORAGE);
    const savedCustomSelectionsStorage = ScriptStorage.get(PERSIST_KEY_CUSTOM_SELECTIONS_STORAGE);
    const savedFirebaseUUID = ScriptStorage.get(PERSIST_KEY_FIREBASE_UUID);
    const firebaseMakeUniqueId = async ({
      db
    }) => {
      let uuid = crypto.randomUUID();
      let snapshot;
      const dbRef = ref(getDatabase());
      try {
        snapshot = await get(child(dbRef, `${VAL_FIREBASE_SYNC_UUID_KEY}/${uuid}`));
        while (snapshot.exists()) {
          uuid = crypto.randomUUID();
          snapshot = await get(child(dbRef, `${VAL_FIREBASE_SYNC_UUID_KEY}/${uuid}`));
        }
      } catch (error2) {
        throw new Error("firebaseMakeUniqueId(): Could not check database");
      }
      try {
        await set(ref(db, `${VAL_FIREBASE_SYNC_UUID_KEY}/${uuid}`), {
          initiated: (/* @__PURE__ */ new Date()).toISOString(),
          userAgent: window.navigator.userAgent
          // To differentiate UUIDs
        });
      } catch (error2) {
        throw new Error("firebaseMakeUniqueId(): Could not write to database");
      }
      return uuid;
    };
    const [firebaseDialogueOpen, setFirebaseDialogueOpen] = h(false);
    const [firebaseUniqueId, setFirebaseUniqueId] = h(savedFirebaseUUID);
    const [firebaseConfig, setFirebaseConfig] = h(null);
    const [firebaseApp, setFirebaseApp] = h(null);
    const [firebaseDb, setFirebaseDb] = h(null);
    const [firebaseSyncedStatistics, setFirebaseSyncedStatistics] = h({});
    const [firebaseSyncedSettings, setFirebaseSyncedSettings] = h({});
    const [firebaseSyncedExercisesStorage, setFirebaseSyncedExercisesStorage] = h([]);
    const [firebaseSyncedSelectionsStorage, setFirebaseSyncedSelectionsStorage] = h([]);
    const firebaseState = {
      dialogueOpen: firebaseDialogueOpen,
      uniqueId: firebaseUniqueId,
      config: firebaseConfig,
      app: firebaseApp,
      db: firebaseDb,
      syncedStatistics: firebaseSyncedStatistics,
      syncedSettings: firebaseSyncedSettings,
      syncedExercisesStorage: firebaseSyncedExercisesStorage,
      syncedSelectionsStorage: firebaseSyncedSelectionsStorage,
      openDialogue: () => {
        setFirebaseDialogueOpen(true);
      },
      closeDialogue: () => {
        setFirebaseDialogueOpen(false);
      },
      initiateUniqueId: async () => {
        if (!firebaseUniqueId) {
          if (!firebaseApp) {
            throw new Error("initiateUniqueId(): FirebaseContextType.app must be set!");
          }
          if (!firebaseDb) {
            throw new Error("initiateUniqueId(): FirebaseContextType.db must be set!");
          }
          try {
            const uuid = await firebaseMakeUniqueId({
              app: firebaseApp,
              db: firebaseDb
            });
            setFirebaseUniqueId(uuid);
          } catch (e2) {
            setFirebaseConfig(null);
            setFirebaseApp(null);
            setFirebaseDb(null);
            ScriptStorage.delete(PERSIST_KEY_ENABLE_FIREBASE_SYNC_SETTING);
            ScriptStorage.delete(PERSIST_KEY_FIREBASE_SYNC_CONF_SETTING);
            ScriptStorage.delete(PERSIST_KEY_FIREBASE_CONFIG);
            ScriptStorage.delete(PERSIST_KEY_FIREBASE_UUID);
          }
        }
      },
      setConfig: (config) => {
        const firebaseApp2 = initializeApp(config);
        const db = getDatabase(firebaseApp2);
        setFirebaseConfig(config);
        setFirebaseApp(firebaseApp2);
        setFirebaseDb(db);
      }
    };
    const [settingsOpen, setSettingsOpen] = h(false);
    const [settingsOptions, setSettingsOptions] = h({
      language: savedSettingLanguage ? savedSettingLanguage : getActiveLanguage(),
      enableCustomSelection: savedSettingEnableCustomSelections ? savedSettingEnableCustomSelections : false,
      enableLoadAllPages: savedSettingEnableLoadAllPages ? savedSettingEnableLoadAllPages : false,
      enableFirebaseSync: savedSettingEnableFirebaseSync ? savedSettingEnableFirebaseSync : false,
      firebaseConfig: savedSettingFirebaseConf ? savedSettingFirebaseConf : null
    });
    const optionsState = {
      open: settingsOpen,
      options: settingsOptions,
      setOpen: () => {
        setSettingsOpen(true);
      },
      setClosed: () => {
        setSettingsOpen(false);
      },
      setOptions: ({
        language = getActiveLanguage(),
        enableCustomSelection = false,
        enableLoadAllPages = false,
        enableFirebaseSync = false,
        firebaseConfig: firebaseConfig2 = null
      }) => {
        setSettingsOptions({
          language,
          enableCustomSelection,
          enableLoadAllPages,
          enableFirebaseSync,
          firebaseConfig: firebaseConfig2
        });
      }
    };
    const [notificationOptions, setNotificationOptions] = h({
      title: "",
      text: "",
      type: NotificationType.NOTIFICATION,
      timeout: 5e3,
      showClose: false
    });
    const notificationState = {
      options: notificationOptions,
      setOptions: ({
        title: title2,
        text,
        type,
        timeout = 5e3,
        showClose = false
      }) => {
        logNotification({
          title: title2,
          text,
          type
        });
        setNotificationOptions({
          title: title2,
          text,
          type,
          timeout,
          showClose
        });
      }
    };
    const [alertOpen, setAlertOpen] = h(false);
    const [alertOptions, setAlertOptions] = h({
      title: "",
      text: "",
      okButtonText: "",
      cancelButtonText: "",
      okCallback: () => {
        return;
      },
      cancelCallback: () => {
        return;
      }
    });
    const alertState = {
      open: alertOpen,
      options: alertOptions,
      setOpen: () => {
        setAlertOpen(true);
      },
      setClosed: () => {
        setAlertOpen(false);
      },
      setOptions: (alertOptions2) => {
        setAlertOptions(alertOptions2);
      }
    };
    const [customSectionsSelectedExercise, setCustomSectionsSelectedExercise] = h(savedCustomSelectionsActiveExercise ? savedCustomSelectionsActiveExercise : {
      exerciseID: "",
      exerciseTitle: ""
    });
    const [customSectionsSelectedSectionIterator, setCustomSectionsSelectedSectionIterator] = h(0);
    const [customSectionsSelectedSections, setCustomSectionsSelectedSections] = h(savedCustomSelectionsActiveSections ? savedCustomSelectionsActiveSections : []);
    const [customSectionsSelectionHash, setCustomSectionsSelectionHash] = h("");
    const [customSectionsSelectionStorageMatch, setCustomSectionsSelectionStorageMatch] = h(null);
    const [customSectionsDialogueSaveSelectionsOpen, setCustomSectionsDialogueSaveSelectionsOpen] = h(false);
    const [customSelectionsStorageDialogueOpen, setCustomSelectionsStorageDialogueOpen] = h(false);
    const [customSelectionsExercisesStorage, setCustomSelectionsExercisesStorage] = h(savedCustomSelectionsExercisesStorage ? savedCustomSelectionsExercisesStorage : []);
    const [customSelectionsStorage, setCustomSelectionsStorage] = h(savedCustomSelectionsStorage ? savedCustomSelectionsStorage : []);
    const customSectionsState = {
      selectedExercise: customSectionsSelectedExercise,
      selectedSectionIterator: customSectionsSelectedSectionIterator,
      selectedSections: customSectionsSelectedSections,
      selectionHash: customSectionsSelectionHash,
      selectionStorageMatch: customSectionsSelectionStorageMatch,
      dialogueSaveSelectionsOpen: customSectionsDialogueSaveSelectionsOpen,
      dialogueCustomSelectionsStorageOpen: customSelectionsStorageDialogueOpen,
      customSelectionsExercisesStorage,
      customSelectionsStorage,
      /* Save Selections Dialogue */
      setDialogueSaveSelectionsOpen: () => {
        setCustomSectionsDialogueSaveSelectionsOpen(true);
      },
      setDialogueSaveSelectionsClosed: () => {
        setCustomSectionsDialogueSaveSelectionsOpen(false);
      },
      /* Selections Storage */
      setDialogueCustomSelectionsStorageOpen: () => {
        setCustomSelectionsStorageDialogueOpen(true);
      },
      setDialogueCustomSelectionsStorageClosed: () => {
        setCustomSelectionsStorageDialogueOpen(false);
      },
      setInCustomSelectionsExercisesStorage: ({
        index: index2 = null,
        exerciseID,
        exerciseTitle
      }) => {
        const currentIndex = index2 !== null && index2 !== void 0 ? index2 : customSelectionsExercisesStorage.length;
        const existingCustomSelectionExercise = getCustomSelectionExerciseFromID({
          exerciseID,
          sectionSelectionContext: customSectionsState
        });
        let updatedExercisesStorage;
        if (!existingCustomSelectionExercise) {
          updatedExercisesStorage = [...customSelectionsExercisesStorage, {
            index: currentIndex,
            exerciseID,
            exerciseTitle
          }];
        } else {
          updatedExercisesStorage = [...filterCustomSelectionExerciseFromID({
            exerciseID,
            sectionSelectionContext: customSectionsState
          }), {
            index: currentIndex,
            exerciseID,
            exerciseTitle
          }];
        }
        updatedExercisesStorage.sort(function(a2, b2) {
          return a2.index - b2.index;
        });
        updatedExercisesStorage = updatedExercisesStorage.map((oneCustomSelectionsExercise, index22) => {
          return {
            ...oneCustomSelectionsExercise,
            index: index22
          };
        });
        setCustomSelectionsExercisesStorage(updatedExercisesStorage);
      },
      setMultipleInCustomSelectionsExercisesStorage: ({
        customSelectionsExercisesStorageSetters,
        resetStorage
      }) => {
        const appendedToStorage = [];
        let filteredFromExistingCustomSelectionsExercises = customSectionsState.customSelectionsExercisesStorage;
        customSelectionsExercisesStorageSetters.forEach(({
          index: index2,
          exerciseID,
          exerciseTitle
        }) => {
          const currentIndex = index2 !== null && index2 !== void 0 ? index2 : customSelectionsExercisesStorage.length;
          const existingCustomSelectionExercise = getCustomSelectionExerciseFromID({
            exerciseID,
            sectionSelectionContext: customSectionsState
          });
          appendedToStorage.push({
            index: currentIndex,
            exerciseID,
            exerciseTitle
          });
          if (!resetStorage && existingCustomSelectionExercise) {
            filteredFromExistingCustomSelectionsExercises = filterCustomSelectionExerciseFromID({
              exerciseID,
              sectionSelectionContext: {
                customSelectionsExercisesStorage: filteredFromExistingCustomSelectionsExercises
              }
            });
          }
        });
        let updatedExercisesStorage;
        if (resetStorage) {
          updatedExercisesStorage = [...appendedToStorage];
        } else {
          updatedExercisesStorage = [...filteredFromExistingCustomSelectionsExercises, ...appendedToStorage];
        }
        updatedExercisesStorage.sort(function(a2, b2) {
          return a2.index - b2.index;
        });
        updatedExercisesStorage = updatedExercisesStorage.map((oneCustomSelectionsExercise, index2) => {
          return {
            ...oneCustomSelectionsExercise,
            index: index2
          };
        });
        setCustomSelectionsExercisesStorage(updatedExercisesStorage);
      },
      deleteFromCustomSelectionsExercisesStorage: ({
        exerciseID
      }) => {
        setCustomSelectionsExercisesStorage(filterCustomSelectionExerciseFromID({
          exerciseID,
          sectionSelectionContext: customSectionsState
        }));
        setCustomSelectionsStorage(filterCustomSelectionFromExerciseID({
          exerciseID,
          sectionSelectionContext: customSectionsState
        }));
      },
      setInCustomSelectionsStorage: ({
        index: index2 = null,
        name: name2,
        exerciseID,
        sections,
        practicesTotal: practicesTotal2,
        practicesToday: practicesToday2,
        lastPracticed: lastPracticed2
      }) => {
        const currentIndex = index2 !== null && index2 !== void 0 ? index2 : customSelectionsStorage.length;
        const customSelectionHash = getCustomSelectionHashFromSelectionContext({
          selectedExercise: {
            exerciseID
          },
          selectedSections: sections
        });
        const existingCustomSelection = getCustomSelectionFromHash({
          hash: customSelectionHash,
          sectionSelectionContext: customSectionsState
        });
        sections.sort(function(a2, b2) {
          return a2.index - b2.index;
        });
        sections = sections.map((oneCustomSelectionsActiveSection, index22) => {
          return {
            ...oneCustomSelectionsActiveSection,
            index: index22
          };
        });
        let updatedStorage;
        if (!existingCustomSelection) {
          updatedStorage = [...customSelectionsStorage, {
            index: currentIndex,
            hash: customSelectionHash,
            name: name2,
            exerciseID,
            sections,
            practicesTotal: practicesTotal2,
            practicesToday: practicesToday2,
            lastPracticed: lastPracticed2
          }];
        } else {
          updatedStorage = [...filterCustomSelectionFromHash({
            hash: customSelectionHash,
            sectionSelectionContext: customSectionsState
          }), {
            index: currentIndex,
            hash: customSelectionHash,
            name: name2,
            exerciseID,
            sections,
            practicesTotal: practicesTotal2,
            practicesToday: practicesToday2,
            lastPracticed: lastPracticed2
          }];
        }
        updatedStorage.sort(function(a2, b2) {
          return a2.index - b2.index;
        });
        updatedStorage = updatedStorage.map((oneCustomSelectionStorage, index22) => {
          return {
            ...oneCustomSelectionStorage,
            index: index22
          };
        });
        setCustomSelectionsStorage(updatedStorage);
      },
      setMultipleInCustomSelectionsStorage: ({
        customSelectionsStorageSetters,
        resetStorage
      }) => {
        const appendedToStorage = [];
        let filteredFromExistingCustomSelections = customSectionsState.customSelectionsStorage;
        customSelectionsStorageSetters.forEach(({
          exerciseID,
          sections,
          name: name2,
          index: index2,
          practicesTotal: practicesTotal2,
          practicesToday: practicesToday2,
          lastPracticed: lastPracticed2
        }, forEachIndex) => {
          const currentIndex = index2 !== null && index2 !== void 0 ? index2 : customSelectionsStorage.length + forEachIndex;
          const customSelectionHash = getCustomSelectionHashFromSelectionContext({
            selectedExercise: {
              exerciseID
            },
            selectedSections: sections
          });
          const existingCustomSelection = getCustomSelectionFromHash({
            hash: customSelectionHash,
            sectionSelectionContext: customSectionsState
          });
          sections.sort(function(a2, b2) {
            return a2.index - b2.index;
          });
          sections = sections.map((oneCustomSelectionsActiveSection, index22) => {
            return {
              ...oneCustomSelectionsActiveSection,
              index: index22
            };
          });
          const entryToAppend = {
            index: currentIndex,
            hash: customSelectionHash,
            name: name2,
            exerciseID,
            sections
          };
          if (practicesTotal2) {
            entryToAppend.practicesTotal = practicesTotal2;
          }
          if (practicesToday2) {
            entryToAppend.practicesToday = practicesToday2;
          }
          if (lastPracticed2) {
            entryToAppend.lastPracticed = lastPracticed2;
          }
          appendedToStorage.push(entryToAppend);
          if (!resetStorage && existingCustomSelection) {
            filteredFromExistingCustomSelections = filterCustomSelectionFromHash({
              hash: customSelectionHash,
              sectionSelectionContext: {
                customSelectionsStorage: filteredFromExistingCustomSelections
              }
            });
          }
        });
        let updatedStorage;
        if (resetStorage) {
          updatedStorage = [...appendedToStorage];
        } else {
          updatedStorage = [...filteredFromExistingCustomSelections, ...appendedToStorage];
        }
        updatedStorage.sort(function(a2, b2) {
          return a2.index - b2.index;
        });
        updatedStorage = updatedStorage.map((oneCustomSelectionStorage, index2) => {
          return {
            ...oneCustomSelectionStorage,
            index: index2
          };
        });
        setCustomSelectionsStorage(updatedStorage);
      },
      deleteFromCustomSelectionsStorage: ({
        hash
      }) => {
        var _a2;
        const exerciseID = (_a2 = getCustomSelectionFromHash({
          hash,
          sectionSelectionContext: customSectionsState
        })) == null ? void 0 : _a2.exerciseID;
        if (exerciseID && getCustomSelectionsFromExerciseID({
          exerciseID,
          sectionSelectionContext: customSectionsState
        }).length === 1) {
          setCustomSelectionsExercisesStorage(filterCustomSelectionExerciseFromID({
            exerciseID,
            sectionSelectionContext: customSectionsState
          }));
        }
        setCustomSelectionsStorage(filterCustomSelectionFromHash({
          hash,
          sectionSelectionContext: customSectionsState
        }));
      },
      setInCustomSelectionSectionsStorage: ({
        hash,
        index: index2,
        sectionID,
        sectionTitle
      }) => {
        const customSelection = getCustomSelectionFromHash({
          hash,
          sectionSelectionContext: customSectionsState
        });
        if (customSelection) {
          const currentIndex = index2 !== null && index2 !== void 0 ? index2 : customSelection.sections.length;
          const existingCustomSelectionSection = customSelection == null ? void 0 : customSelection.sections.filter(propFilterSectionID(sectionID));
          let updatedSectionsStorage;
          if (!existingCustomSelectionSection || existingCustomSelectionSection.length === 0) {
            updatedSectionsStorage = [...customSelection.sections, {
              index: currentIndex,
              sectionID,
              sectionTitle
            }];
          } else {
            updatedSectionsStorage = [...customSelection.sections.filter(propFilterSectionID(sectionID)), {
              index: currentIndex,
              sectionID,
              sectionTitle
            }];
          }
          updatedSectionsStorage.sort(function(a2, b2) {
            return a2.index - b2.index;
          });
          updatedSectionsStorage = updatedSectionsStorage.map((oneCustomSelectionSection, index22) => {
            return {
              ...oneCustomSelectionSection,
              index: index22
            };
          });
          const updatedCustomSelectionHash = getCustomSelectionHashFromSelectionContext({
            selectedExercise: {
              exerciseID: customSelection.exerciseID
            },
            selectedSections: updatedSectionsStorage
          });
          let updatedCustomSelectionsStorage = [...filterCustomSelectionFromHash({
            hash,
            sectionSelectionContext: customSectionsState
          }), {
            ...customSelection,
            sections: updatedSectionsStorage,
            hash: updatedCustomSelectionHash
          }];
          updatedCustomSelectionsStorage.sort(function(a2, b2) {
            return a2.index - b2.index;
          });
          updatedCustomSelectionsStorage = updatedCustomSelectionsStorage.map((oneCustomSelectionStorage, index22) => {
            return {
              ...oneCustomSelectionStorage,
              index: index22
            };
          });
          setCustomSelectionsStorage(updatedCustomSelectionsStorage);
        }
      },
      setMultipleInCustomSelectionSectionsStorage: (customSelectionsSectionStorageSetters) => {
        const uniqueHashes = customSelectionsSectionStorageSetters.map(({
          hash
        }) => hash).filter((hash, index2, array) => array.indexOf(hash) === index2);
        const customSelectionsToUpdate = [];
        uniqueHashes.forEach((hash) => {
          const customSelection = getCustomSelectionFromHash({
            hash,
            sectionSelectionContext: customSectionsState
          });
          if (customSelection) {
            customSelectionsToUpdate.push(customSelection);
          }
        });
        const appendedToStorage = [];
        let filteredFromExistingCustomSelections = customSectionsState.customSelectionsStorage;
        customSelectionsToUpdate.forEach((customSelection) => {
          const customSelectionSectionsToUpdate = customSelectionsSectionStorageSetters.filter(propFilterCustomSelectionHash(customSelection.hash));
          const appendedToSections = [];
          let filteredFromExistingSections = customSelection.sections;
          customSelectionSectionsToUpdate.forEach(({
            index: index2,
            sectionID,
            sectionTitle
          }) => {
            const currentIndex = index2 !== null && index2 !== void 0 ? index2 : customSelection.sections.length;
            const existingCustomSelectionSection = customSelection == null ? void 0 : customSelection.sections.filter(propFilterSectionID(sectionID));
            appendedToSections.push({
              index: currentIndex,
              sectionID,
              sectionTitle
            });
            if (existingCustomSelectionSection) {
              filteredFromExistingSections = filteredFromExistingSections.filter(propFilterSectionID(sectionID));
            }
          });
          let updatedSectionsStorage = [...filteredFromExistingSections, ...appendedToSections];
          updatedSectionsStorage.sort(function(a2, b2) {
            return a2.index - b2.index;
          });
          updatedSectionsStorage = updatedSectionsStorage.map((oneCustomSelectionSection, index2) => {
            return {
              ...oneCustomSelectionSection,
              index: index2
            };
          });
          const updatedCustomSelectionHash = getCustomSelectionHashFromSelectionContext({
            selectedExercise: {
              exerciseID: customSelection.exerciseID
            },
            selectedSections: updatedSectionsStorage
          });
          const existingCustomSelection = getCustomSelectionFromHash({
            hash: customSelection.hash,
            sectionSelectionContext: customSectionsState
          });
          appendedToStorage.push({
            ...customSelection,
            hash: updatedCustomSelectionHash,
            sections: updatedSectionsStorage
          });
          if (existingCustomSelection) {
            filteredFromExistingCustomSelections = filterCustomSelectionFromHash({
              hash: customSelection.hash,
              sectionSelectionContext: {
                customSelectionsStorage: filteredFromExistingCustomSelections
              }
            });
          }
        });
        let updatedStorage = [...filteredFromExistingCustomSelections, ...appendedToStorage];
        updatedStorage.sort(function(a2, b2) {
          return a2.index - b2.index;
        });
        updatedStorage = updatedStorage.map((oneCustomSelectionStorage, index2) => {
          return {
            ...oneCustomSelectionStorage,
            index: index2
          };
        });
        setCustomSelectionsStorage(updatedStorage);
      },
      deleteFromCustomSelectionSectionsStorage: ({
        hash,
        sectionID
      }) => {
        const customSelection = getCustomSelectionFromHash({
          hash,
          sectionSelectionContext: customSectionsState
        });
        if (customSelection) {
          const updatedSections = customSelection.sections.filter(propFilterSectionID(sectionID));
          if (customSelection.sections.length !== updatedSections.length) {
            const customSelectionFixedSections = {
              ...customSelection,
              sections: updatedSections
            };
            customSelectionFixedSections.sections.sort(function(a2, b2) {
              return a2.index - b2.index;
            });
            customSelectionFixedSections.sections = customSelectionFixedSections.sections.map((oneCustomSelectionSection, index2) => {
              return {
                ...oneCustomSelectionSection,
                index: index2
              };
            });
            const updatedCustomSelectionHash = getCustomSelectionHashFromSelectionContext({
              selectedExercise: {
                exerciseID: customSelectionFixedSections.exerciseID
              },
              selectedSections: customSelectionFixedSections.sections
            });
            let updatedStorage = [...filterCustomSelectionFromHash({
              hash,
              sectionSelectionContext: customSectionsState
            }), {
              ...customSelectionFixedSections,
              hash: updatedCustomSelectionHash
            }];
            updatedStorage.sort(function(a2, b2) {
              return a2.index - b2.index;
            });
            updatedStorage = updatedStorage.map((oneCustomSelectionStorage, index2) => {
              return {
                ...oneCustomSelectionStorage,
                index: index2
              };
            });
            setCustomSelectionsStorage(updatedStorage);
          }
        }
      },
      updateLastPracticedInCustomSelectionsStorage: ({
        hash
      }) => {
        const existingCustomSelection = getCustomSelectionFromHash({
          hash,
          sectionSelectionContext: customSectionsState
        });
        if (existingCustomSelection) {
          const currentTimestamp = (/* @__PURE__ */ new Date()).toISOString();
          existingCustomSelection.practicesTotal = existingCustomSelection.practicesTotal ? existingCustomSelection.practicesTotal + 1 : 1;
          if (!existingCustomSelection.lastPracticed || !existingCustomSelection.practicesToday) {
            existingCustomSelection.practicesToday = 1;
          } else {
            if (!isDateToday(new Date(existingCustomSelection.lastPracticed))) {
              existingCustomSelection.practicesToday = 1;
            } else {
              existingCustomSelection.practicesToday += 1;
            }
          }
          existingCustomSelection.lastPracticed = currentTimestamp;
          const updatedStorage = [...filterCustomSelectionFromHash({
            hash,
            sectionSelectionContext: customSectionsState
          }), existingCustomSelection];
          updatedStorage.sort(function(a2, b2) {
            return a2.index - b2.index;
          });
          setCustomSelectionsStorage(updatedStorage);
        }
      },
      getCustomSelectionsStatistics: ({
        hash
      }) => {
        const existingCustomSelection = getCustomSelectionFromHash({
          hash,
          sectionSelectionContext: customSectionsState
        });
        if (existingCustomSelection) {
          return {
            lastPracticed: existingCustomSelection.lastPracticed ? existingCustomSelection.lastPracticed : null,
            practicesToday: existingCustomSelection.practicesToday ? existingCustomSelection.practicesToday : 0,
            practicesTotal: existingCustomSelection.practicesTotal ? existingCustomSelection.practicesTotal : 0
          };
        }
        return {
          lastPracticed: null,
          practicesToday: 0,
          practicesTotal: 0
        };
      },
      /* Selections */
      reset: () => {
        setCustomSectionsSelectedExercise({
          exerciseID: "",
          exerciseTitle: ""
        });
        setCustomSectionsSelectedSectionIterator(0);
        setCustomSectionsSelectedSections([]);
      },
      resetAndAddToSelectedSections: ({
        elementID,
        sectionID,
        sectionTitle
      }) => {
        setCustomSectionsSelectedSections([{
          index: 0,
          elementID,
          sectionID,
          sectionTitle
        }]);
        setCustomSectionsSelectedSectionIterator(1);
      },
      setSelectedExercise: (props) => {
        setCustomSectionsSelectedExercise(props);
      },
      addToSelectedSections: ({
        elementID,
        sectionID,
        sectionTitle
      }) => {
        const updatedCustomSectionsSelectedSections = [...customSectionsSelectedSections, {
          index: customSectionsSelectedSectionIterator,
          elementID,
          sectionID,
          sectionTitle
        }];
        setCustomSectionsSelectedSections(updatedCustomSectionsSelectedSections);
        setCustomSectionsSelectedSectionIterator(customSectionsSelectedSectionIterator + 1);
      },
      setMultipleSelectedSections: (customSelectionSectionAdditions) => {
        setCustomSectionsSelectedSections(customSelectionSectionAdditions);
        setCustomSectionsSelectedSectionIterator(customSelectionSectionAdditions.length);
      },
      removeFromSelectedSections: ({
        elementID
      }) => {
        const updatedCustomSectionsSelectedSections = customSectionsSelectedSections.filter(propFilterElementID(elementID));
        setCustomSectionsSelectedSections(updatedCustomSectionsSelectedSections);
      }
    };
    p(() => {
      if (settingsOptions.language) {
        ScriptStorage.set(PERSIST_KEY_LANGUAGE_SETTING, settingsOptions.language);
      } else {
        ScriptStorage.delete(PERSIST_KEY_LANGUAGE_SETTING);
      }
      if (settingsOptions.enableCustomSelection) {
        ScriptStorage.set(PERSIST_KEY_ENABLE_CUSTOM_SELECTIONS_SETTING, settingsOptions.enableCustomSelection);
      } else {
        ScriptStorage.delete(PERSIST_KEY_ENABLE_CUSTOM_SELECTIONS_SETTING);
      }
      if (settingsOptions.enableLoadAllPages) {
        ScriptStorage.set(PERSIST_KEY_ENABLE_LOAD_ALL_PAGES_SETTING, settingsOptions.enableLoadAllPages);
      } else {
        ScriptStorage.delete(PERSIST_KEY_ENABLE_LOAD_ALL_PAGES_SETTING);
      }
      if (settingsOptions.enableFirebaseSync) {
        ScriptStorage.set(PERSIST_KEY_ENABLE_FIREBASE_SYNC_SETTING, settingsOptions.enableFirebaseSync);
      } else {
        ScriptStorage.delete(PERSIST_KEY_ENABLE_FIREBASE_SYNC_SETTING);
      }
      if (settingsOptions.firebaseConfig) {
        ScriptStorage.set(PERSIST_KEY_FIREBASE_SYNC_CONF_SETTING, settingsOptions.firebaseConfig);
      } else {
        ScriptStorage.delete(PERSIST_KEY_FIREBASE_SYNC_CONF_SETTING);
      }
    }, [settingsOptions]);
    p(() => {
      const hash = getCustomSelectionHashFromSelectionContext({
        selectedExercise: customSectionsSelectedExercise,
        selectedSections: customSectionsSelectedSections
      });
      const existingCustomSelection = getCustomSelectionFromHash({
        hash,
        sectionSelectionContext: {
          customSelectionsStorage
        }
      });
      if (existingCustomSelection) {
        setCustomSectionsSelectionStorageMatch(existingCustomSelection);
      } else {
        setCustomSectionsSelectionStorageMatch(null);
      }
      setCustomSectionsSelectionHash(hash);
    }, [customSectionsSelectedExercise, customSectionsSelectedSections, customSelectionsStorage]);
    p(() => {
      if (customSelectionsExercisesStorage.length === 0) {
        ScriptStorage.delete(PERSIST_KEY_CUSTOM_SELECTIONS_EXERCISES_STORAGE);
      } else {
        ScriptStorage.set(PERSIST_KEY_CUSTOM_SELECTIONS_EXERCISES_STORAGE, customSelectionsExercisesStorage);
      }
    }, [customSelectionsExercisesStorage]);
    p(() => {
      if (customSelectionsStorage.length === 0) {
        ScriptStorage.delete(PERSIST_KEY_CUSTOM_SELECTIONS_STORAGE);
      } else {
        ScriptStorage.set(PERSIST_KEY_CUSTOM_SELECTIONS_STORAGE, customSelectionsStorage);
      }
    }, [customSelectionsStorage]);
    p(() => {
      if (customSectionsSelectedSections.length === 0) {
        ScriptStorage.delete(PERSIST_KEY_CUSTOM_SELECTIONS_ACTIVE_SECTIONS);
      } else {
        ScriptStorage.set(PERSIST_KEY_CUSTOM_SELECTIONS_ACTIVE_SECTIONS, customSectionsSelectedSections);
      }
    }, [customSectionsSelectedSections]);
    p(() => {
      if (customSectionsSelectedExercise.exerciseID.length === 0) {
        ScriptStorage.delete(PERSIST_KEY_CUSTOM_SELECTIONS_ACTIVE_EXERCISE);
      } else {
        ScriptStorage.set(PERSIST_KEY_CUSTOM_SELECTIONS_ACTIVE_EXERCISE, customSectionsSelectedExercise);
      }
    }, [customSectionsSelectedExercise]);
    p(() => {
      const savedFirebaseConf = ScriptStorage.get(PERSIST_KEY_FIREBASE_CONFIG);
      if (!firebaseApp && !firebaseDb) {
        if (savedFirebaseConf) {
          firebaseState.setConfig(savedFirebaseConf);
        }
      }
    }, []);
    p(() => {
      if (firebaseConfig && firebaseApp && firebaseDb && firebaseUniqueId) {
        const sharedSettingsRef = ref(firebaseDb, `${VAL_FIREBASE_SYNC_SETTINGS_KEY}/${VAL_FIREBASE_SYNC_SHARED_KEY}`);
        onValue(sharedSettingsRef, (snapshot) => {
          const data = snapshot.val();
          if (data) {
            setFirebaseSyncedSettings(data);
          }
        });
        const sharedCustomSelectionsExercisesRef = ref(firebaseDb, `${VAL_FIREBASE_SYNC_CUSTOM_SELECTIONS_EXERCISES_STORAGE_KEY}/${VAL_FIREBASE_SYNC_SHARED_KEY}`);
        onValue(sharedCustomSelectionsExercisesRef, (snapshot) => {
          const data = snapshot.val();
          if (data) {
            setFirebaseSyncedExercisesStorage(data);
          }
        });
        const sharedCustomSelectionsRef = ref(firebaseDb, `${VAL_FIREBASE_SYNC_CUSTOM_SELECTIONS_STORAGE_KEY}/${VAL_FIREBASE_SYNC_SHARED_KEY}`);
        onValue(sharedCustomSelectionsRef, (snapshot) => {
          const data = snapshot.val();
          if (data) {
            setFirebaseSyncedSelectionsStorage(data);
          }
        });
        const customSelectionsStorageRef = ref(firebaseDb, `${VAL_FIREBASE_SYNC_CUSTOM_SELECTIONS_STORAGE_KEY}`);
        onValue(customSelectionsStorageRef, (snapshot) => {
          const data = snapshot.val();
          if (data) {
            const syncedStatistics = {};
            Object.keys(data).filter((key) => ![firebaseUniqueId, VAL_FIREBASE_SYNC_SHARED_KEY].includes(key)).forEach((uuid) => {
              data[uuid].forEach(({
                hash,
                lastPracticed: lastPracticed2,
                practicesToday: practicesToday2,
                practicesTotal: practicesTotal2
              }) => {
                const curStatistics = hash in syncedStatistics ? syncedStatistics[hash] : {
                  lastPracticed: null,
                  practicesToday: 0,
                  practicesTotal: 0
                };
                if (!curStatistics.lastPracticed && lastPracticed2 || curStatistics.lastPracticed && lastPracticed2 && new Date(lastPracticed2).getDate() > new Date(curStatistics.lastPracticed).getDate()) {
                  curStatistics.lastPracticed = lastPracticed2;
                }
                if (lastPracticed2 && isDateToday(new Date(lastPracticed2)) && practicesToday2) {
                  curStatistics.practicesToday += practicesToday2;
                }
                if (practicesTotal2) {
                  curStatistics.practicesTotal += practicesTotal2;
                }
                syncedStatistics[hash] = curStatistics;
              });
            });
            setFirebaseSyncedStatistics(syncedStatistics);
          }
        });
      } else if (firebaseConfig && firebaseApp && firebaseDb) {
        firebaseState.initiateUniqueId();
      }
    }, [firebaseConfig, firebaseApp, firebaseDb, firebaseUniqueId]);
    p(() => {
      if (!firebaseUniqueId || firebaseUniqueId.length === 0) {
        ScriptStorage.delete(PERSIST_KEY_FIREBASE_UUID);
      } else {
        ScriptStorage.set(PERSIST_KEY_FIREBASE_UUID, firebaseUniqueId);
      }
    }, [firebaseUniqueId]);
    p(() => {
      if (firebaseDb && firebaseUniqueId) {
        const dataToSave = {
          language: settingsOptions.language
        };
        set(ref(firebaseDb, `${VAL_FIREBASE_SYNC_SETTINGS_KEY}/${firebaseUniqueId}`), dataToSave);
      }
    }, [settingsOptions.language]);
    p(() => {
      if (firebaseDb && firebaseUniqueId) {
        set(ref(firebaseDb, `${VAL_FIREBASE_SYNC_CUSTOM_SELECTIONS_EXERCISES_STORAGE_KEY}/${firebaseUniqueId}`), customSelectionsExercisesStorage);
      }
    }, [customSelectionsExercisesStorage]);
    p(() => {
      if (firebaseDb && firebaseUniqueId) {
        set(ref(firebaseDb, `${VAL_FIREBASE_SYNC_CUSTOM_SELECTIONS_STORAGE_KEY}/${firebaseUniqueId}`), customSelectionsStorage);
      }
    }, [customSelectionsStorage]);
    return o(FirebaseContext.Provider, {
      value: firebaseState,
      children: o(NotificationContext.Provider, {
        value: notificationState,
        children: o(AlertContext.Provider, {
          value: alertState,
          children: o(SettingsContext.Provider, {
            value: optionsState,
            children: o(SectionSelectionContext.Provider, {
              value: customSectionsState,
              children: [o(MainUserscriptComponent, {}), wlTopBarElement && verifyOnLoggedInPage() && !verifyOnPagePractice() && z(o("ul", {
                className: "TopBarContainer",
                children: [o(SettingsContext.Consumer, {
                  children: (settingsContext) => o(WordalistMenuPortal, {
                    id: ELEM_LOGGED_IN_TOP_BAR_CONTAINER_ITEM_WLE_SETTINGS_ID,
                    onClickCallback: () => {
                      settingsContext.setOpen();
                    },
                    children: o(GearIcon, {})
                  })
                }), settingsOptions.enableCustomSelection && o(SectionSelectionContext.Consumer, {
                  children: (sectionSelectionContext) => o(WordalistMenuPortal, {
                    id: ELEM_LOGGED_IN_TOP_BAR_CONTAINER_ITEM_WLE_SELECTION_ID,
                    onClickCallback: () => {
                      sectionSelectionContext.setDialogueCustomSelectionsStorageOpen();
                    },
                    children: o(BookmarkIcon, {})
                  })
                }), settingsOptions.enableFirebaseSync && o(FirebaseContext.Consumer, {
                  children: (firebaseContext) => o(WordalistMenuPortal, {
                    id: ELEM_LOGGED_IN_TOP_BAR_CONTAINER_ITEM_WLE_SYNCHRONIZATION_ID,
                    onClickCallback: () => {
                      firebaseContext.openDialogue();
                    },
                    children: o(UpdateIcon, {})
                  })
                })]
              }), wlTopBarElement), settingsOptions.enableCustomSelection && !verifyOnPagePractice() && wlPersonalMenuElement && z(o(SectionSelectionContext.Consumer, {
                children: (sectionSelectionContext) => o(WordalistMenuPortal, {
                  id: ELEM_PERSONAL_MENU_ITEM_WLE_SELECTION_ID,
                  onClickCallback: sectionSelectionContext.setDialogueCustomSelectionsStorageOpen,
                  children: instance.t(`${LANG_NS_MAIN}:menuWLESelection`)
                })
              }), wlPersonalMenuElement), settingsOptions.enableFirebaseSync && !verifyOnPagePractice() && wlPersonalMenuElement && z(o(FirebaseContext.Consumer, {
                children: (firebaseContext) => o(WordalistMenuPortal, {
                  id: ELEM_PERSONAL_MENU_ITEM_WLE_SYNCHRONIZATION_ID,
                  onClickCallback: () => {
                    firebaseContext.openDialogue();
                  },
                  children: instance.t(`${LANG_NS_MAIN}:menuWLESynchronization`)
                })
              }), wlPersonalMenuElement), !verifyOnPagePractice() && wlBottomMenuElement && z(o(SettingsContext.Consumer, {
                children: (settingsContext) => o(WordalistMenuPortal, {
                  id: ELEM_BOTTOM_MENU_ITEM_WLE_SETTINGS_ID,
                  onClickCallback: settingsContext.setOpen,
                  children: instance.t(`${LANG_NS_MAIN}:menuWLESettings`)
                })
              }), wlBottomMenuElement), settingsOptions.enableCustomSelection && verifyOnPageExercise() && z(o(CustomSelectionsToolbar, {}), wlPageExerciseToolbarContainerElement), settingsOptions.enableCustomSelection && verifyOnPageExercise() && wlPageExerciseSectionsAddedPortals, settingsOptions.enableLoadAllPages && verifyOnPageExerciseExploreSection() && z(o(ExploreSectionsToolbar, {}), wlPageExerciseExploreSectionToolbarContainerElement)]
            })
          })
        })
      })
    });
  };
  D$1(o(UserscriptApp, {}), (() => {
    const mainApp = document.createElement("div");
    mainApp.id = ELEM_MAIN_APP_ID;
    document.body.append(mainApp);
    return mainApp;
  })());

})();